Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Swagger generation for array of embedded objects with empty array as default value #11

Merged
merged 1 commit into from
Jul 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}
}
Loading