Skip to content

Commit

Permalink
Fix Swagger generation for array of embedded objects with empty array…
Browse files Browse the repository at this point in the history
… as default value
  • Loading branch information
pidhorodetskyi committed Jun 25, 2024
1 parent 09f8ba3 commit ee2338a
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions ApiDoc/Components.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

namespace Auto1\ServiceAPIHandlerBundle\ApiDoc;

use OpenApi\Generator;
use Symfony\Component\PropertyInfo\Type;

class Components extends \OpenApi\Annotations\Components
{
public function validate(array $stack = [], array $skip = [], string $ref = '', $context = null): bool
Expand All @@ -15,4 +18,46 @@ public function validate(array $stack = [], array $skip = [], string $ref = '',
*/
return true;
}

public function jsonSerialize()
{
/**
* If response dto has property `$entities` with type `Entity[]` and with default value as empty array
* swagger file will be generated with empty array and not with `Entity[]` schema
* ```
* {
* "entities": []
* }
* ```
* This part of code will replace empty array with `Generator::UNDEFINED`
* and swagger file will generate proper `Entity[]` schema
*
* ```
* {
* "entities": [
* {
* "propertyId": 0,
* "branchId": 0,
* ....
* }
* ]
* }
* ```
*/
if (property_exists($this, 'schemas') && is_array($this->schemas)) {
foreach ($this->schemas as $schema) {
if (!property_exists($schema, 'properties') || !is_array($schema->properties)) {
continue;
}

foreach ($schema->properties as $property) {
if ($property->type == Type::BUILTIN_TYPE_ARRAY || $property->default == []) {
$property->default = Generator::UNDEFINED;
}
}
}
}

return parent::jsonSerialize();
}
}

0 comments on commit ee2338a

Please sign in to comment.