|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace ApiPlatform\JsonSchema; |
| 15 | + |
| 16 | +use ApiPlatform\Metadata\Operation; |
| 17 | + |
| 18 | +/** |
| 19 | + * This factory decorates range integer and number properties to keep Draft 4 backward compatibility. |
| 20 | + * |
| 21 | + * @see https://github.com/api-platform/core/issues/6041 |
| 22 | + * |
| 23 | + * @internal |
| 24 | + */ |
| 25 | +final class BackwardCompatibleSchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareInterface |
| 26 | +{ |
| 27 | + public const SCHEMA_DRAFT4_VERSION = 'draft_4'; |
| 28 | + |
| 29 | + public function __construct(private readonly SchemaFactoryInterface $decorated) |
| 30 | + { |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * {@inheritDoc} |
| 35 | + */ |
| 36 | + 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 |
| 37 | + { |
| 38 | + $schema = $this->decorated->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection); |
| 39 | + |
| 40 | + if (!($serializerContext[self::SCHEMA_DRAFT4_VERSION] ?? false)) { |
| 41 | + return $schema; |
| 42 | + } |
| 43 | + |
| 44 | + foreach ($schema->getDefinitions() as $definition) { |
| 45 | + foreach ($definition['properties'] ?? [] as $property) { |
| 46 | + if (isset($property['type']) && \in_array($property['type'], ['integer', 'number'], true)) { |
| 47 | + if (isset($property['exclusiveMinimum'])) { |
| 48 | + $property['minimum'] = $property['exclusiveMinimum']; |
| 49 | + $property['exclusiveMinimum'] = true; |
| 50 | + } |
| 51 | + if (isset($property['exclusiveMaximum'])) { |
| 52 | + $property['maximum'] = $property['exclusiveMaximum']; |
| 53 | + $property['exclusiveMaximum'] = true; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return $schema; |
| 60 | + } |
| 61 | + |
| 62 | + public function setSchemaFactory(SchemaFactoryInterface $schemaFactory): void |
| 63 | + { |
| 64 | + if ($this->decorated instanceof SchemaFactoryAwareInterface) { |
| 65 | + $this->decorated->setSchemaFactory($schemaFactory); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments