Skip to content

Commit

Permalink
Add support for dictionaries (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
bastien-phi authored Jan 29, 2024
1 parent 46d8268 commit 7e94dd7
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Validation/AbstractValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ protected function filterProperties(object $data, ?string $mode = null): object
return $data;
}

if (isset($data->type) && $data->type === 'object') {
$data->properties ??= new \stdClass();
}

if (! isset($data->properties)) {
return $data;
}
Expand Down
25 changes: 25 additions & 0 deletions tests/Fixtures/Dictionary.v1.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
openapi: 3.0.0
info:
title: Dictionary.v1
version: '1.0'
servers:
- url: 'http://localhost:3000'
paths:
/dictionary-of-integers:
get:
summary: Get dictionary of integers
tags: [ ]
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
data:
type: object
additionalProperties:
type: integer
components:
schemas: {}
42 changes: 42 additions & 0 deletions tests/ResponseValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -830,4 +830,46 @@ public static function requiredWriteOnlySchemaProvider(): array
],
];
}

/**
* @dataProvider objectAsDictionaryProvider
*/
public function test_object_as_dictionary(mixed $payload, bool $isValid): void
{
Spectator::using('Dictionary.v1.yml');

Route::get('/dictionary-of-integers', static function () use ($payload) {
return ['data' => $payload];
})->middleware(Middleware::class);

if ($isValid) {
$this->getJson('/dictionary-of-integers')
->assertValidResponse();
} else {
$this->getJson('/dictionary-of-integers')
->assertInvalidResponse();
}
}

public static function objectAsDictionaryProvider(): array
{
return [
'valid' => [
['foo' => 1, 'bar' => -1],
true,
],
'invalid as string' => [
'foo',
false,
],
'invalid as array' => [
[1, 2],
false,
],
'invalid as dictionary of string' => [
['foo' => 'foo', 'bar' => 'bar'],
false,
],
];
}
}

0 comments on commit 7e94dd7

Please sign in to comment.