. */ declare(strict_types=1); namespace App\ApiPlatform; use ApiPlatform\JsonSchema\Schema; use ApiPlatform\JsonSchema\SchemaFactoryInterface; use ApiPlatform\Metadata\Operation; use Symfony\Component\DependencyInjection\Attribute\AsDecorator; /** * This decorator adds the properties given by DocumentedAPIProperty attributes on the classes to the schema. */ #[AsDecorator('api_platform.json_schema.schema_factory')] class AddDocumentedAPIPropertiesJSONSchemaFactory implements SchemaFactoryInterface { public function __construct(private readonly SchemaFactoryInterface $decorated) { } public function buildSchema( string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, Operation $operation = null, Schema $schema = null, array $serializerContext = null, bool $forceCollection = false ): Schema { $schema = $this->decorated->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection); //Check if there is are DocumentedAPIProperty attributes on the class $reflectionClass = new \ReflectionClass($className); $attributes = $reflectionClass->getAttributes(DocumentedAPIProperty::class); foreach ($attributes as $attribute) { /** @var DocumentedAPIProperty $api_property */ $api_property = $attribute->newInstance(); $this->addPropertyToSchema($schema, $api_property->schemaName, $api_property->property, $api_property, $serializerContext ?? [], $format); } return $schema; } private function addPropertyToSchema(Schema $schema, string $definitionName, string $normalizedPropertyName, DocumentedAPIProperty $propertyMetadata, array $serializerContext, string $format): void { $version = $schema->getVersion(); $swagger = Schema::VERSION_SWAGGER === $version; $propertySchema = []; if (false === $propertyMetadata->writeable) { $propertySchema['readOnly'] = true; } if (!$swagger && false === $propertyMetadata->readable) { $propertySchema['writeOnly'] = true; } if (null !== $description = $propertyMetadata->description) { $propertySchema['description'] = $description; } $deprecationReason = $propertyMetadata->deprecationReason; // see https://github.com/json-schema-org/json-schema-spec/pull/737 if (!$swagger && null !== $deprecationReason) { $propertySchema['deprecated'] = true; } if (!empty($default = $propertyMetadata->default)) { if ($default instanceof \BackedEnum) { $default = $default->value; } $propertySchema['default'] = $default; } if (!empty($example = $propertyMetadata->example)) { $propertySchema['example'] = $example; } if (!isset($propertySchema['example']) && isset($propertySchema['default'])) { $propertySchema['example'] = $propertySchema['default']; } $propertySchema['type'] = $propertyMetadata->type; $propertySchema['nullable'] = $propertyMetadata->nullable; $propertySchema = new \ArrayObject($propertySchema); $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = $propertySchema; } }