vendor/api-platform/core/src/Core/JsonSchema/SchemaFactory.php line 61

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Core\JsonSchema;
  12. use ApiPlatform\Api\ResourceClassResolverInterface;
  13. use ApiPlatform\Core\Api\OperationType;
  14. use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface as LegacyPropertyMetadataFactoryInterface;
  15. use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface as LegacyPropertyNameCollectionFactoryInterface;
  16. use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
  17. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  18. use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
  19. use ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer;
  20. use ApiPlatform\JsonSchema\TypeFactoryInterface;
  21. use ApiPlatform\Metadata\ApiProperty;
  22. use ApiPlatform\Metadata\HttpOperation;
  23. use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
  24. use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
  25. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  26. use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
  27. use ApiPlatform\OpenApi\Factory\OpenApiFactory;
  28. use ApiPlatform\Util\ResourceClassInfoTrait;
  29. use Symfony\Component\PropertyInfo\Type;
  30. use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
  31. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  32. /**
  33.  * @experimental
  34.  *
  35.  * @author Kévin Dunglas <dunglas@gmail.com>
  36.  */
  37. final class SchemaFactory implements SchemaFactoryInterface
  38. {
  39.     use ResourceClassInfoTrait;
  40.     private $typeFactory;
  41.     /**
  42.      * @var LegacyPropertyNameCollectionFactoryInterface|PropertyNameCollectionFactoryInterface
  43.      */
  44.     private $propertyNameCollectionFactory;
  45.     /**
  46.      * @var LegacyPropertyMetadataFactoryInterface|PropertyMetadataFactoryInterface
  47.      */
  48.     private $propertyMetadataFactory;
  49.     private $nameConverter;
  50.     private $distinctFormats = [];
  51.     /**
  52.      * @param TypeFactoryInterface $typeFactory
  53.      */
  54.     public function __construct($typeFactory$resourceMetadataFactory$propertyNameCollectionFactory$propertyMetadataFactoryNameConverterInterface $nameConverter nullResourceClassResolverInterface $resourceClassResolver null)
  55.     {
  56.         $this->typeFactory $typeFactory;
  57.         if (!$resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  58.             trigger_deprecation('api-platform/core''2.7'sprintf('Use "%s" instead of "%s".'ResourceMetadataCollectionFactoryInterface::class, ResourceMetadataFactoryInterface::class));
  59.         }
  60.         $this->resourceMetadataFactory $resourceMetadataFactory;
  61.         $this->propertyNameCollectionFactory $propertyNameCollectionFactory;
  62.         $this->propertyMetadataFactory $propertyMetadataFactory;
  63.         $this->nameConverter $nameConverter;
  64.         $this->resourceClassResolver $resourceClassResolver;
  65.     }
  66.     /**
  67.      * When added to the list, the given format will lead to the creation of a new definition.
  68.      *
  69.      * @internal
  70.      */
  71.     public function addDistinctFormat(string $format): void
  72.     {
  73.         $this->distinctFormats[$format] = true;
  74.     }
  75.     public function buildSchema(string $classNamestring $format 'json'string $type Schema::TYPE_OUTPUTstring $operationType nullstring $operationName nullSchema $schema null, array $serializerContext nullbool $forceCollection false): Schema
  76.     {
  77.         $schema $schema ? clone $schema : new Schema();
  78.         if (null === $metadata $this->getMetadata($className$type$operationType$operationName$serializerContext)) {
  79.             return $schema;
  80.         }
  81.         [$resourceMetadata$serializerContext$validationGroups$inputOrOutputClass] = $metadata;
  82.         if (null === $resourceMetadata && (null !== $operationType || null !== $operationName)) {
  83.             throw new \LogicException('The $operationType and $operationName arguments must be null for non-resource class.');
  84.         }
  85.         $operation $resourceMetadata instanceof ResourceMetadataCollection $resourceMetadata->getOperation($operationNameOperationType::COLLECTION === $operationType) : null;
  86.         $version $schema->getVersion();
  87.         $definitionName $this->buildDefinitionName($className$format$inputOrOutputClass$resourceMetadata instanceof ResourceMetadata $resourceMetadata $operation$serializerContext);
  88.         $method $operation instanceof HttpOperation $operation->getMethod() : 'GET';
  89.         if (!$operation && (null === $operationType || null === $operationName)) {
  90.             $method Schema::TYPE_INPUT === $type 'POST' 'GET';
  91.         } elseif ($resourceMetadata instanceof ResourceMetadata) {
  92.             $method $resourceMetadata->getTypedOperationAttribute($operationType$operationName'method''GET');
  93.         }
  94.         if (Schema::TYPE_OUTPUT !== $type && !\in_array($method, ['POST''PATCH''PUT'], true)) {
  95.             return $schema;
  96.         }
  97.         if (!isset($schema['$ref']) && !isset($schema['type'])) {
  98.             $ref Schema::VERSION_OPENAPI === $version '#/components/schemas/'.$definitionName '#/definitions/'.$definitionName;
  99.             if ($forceCollection || (OperationType::COLLECTION === $operationType && 'POST' !== $method)) {
  100.                 $schema['type'] = 'array';
  101.                 $schema['items'] = ['$ref' => $ref];
  102.             } else {
  103.                 $schema['$ref'] = $ref;
  104.             }
  105.         }
  106.         $definitions $schema->getDefinitions();
  107.         if (isset($definitions[$definitionName])) {
  108.             // Already computed
  109.             return $schema;
  110.         }
  111.         /** @var \ArrayObject<string, mixed> $definition */
  112.         $definition = new \ArrayObject(['type' => 'object']);
  113.         $definitions[$definitionName] = $definition;
  114.         if ($resourceMetadata instanceof ResourceMetadata) {
  115.             $definition['description'] = $resourceMetadata->getDescription() ?? '';
  116.         } else {
  117.             $definition['description'] = $operation ? ($operation->getDescription() ?? '') : '';
  118.         }
  119.         // additionalProperties are allowed by default, so it does not need to be set explicitly, unless allow_extra_attributes is false
  120.         // See https://json-schema.org/understanding-json-schema/reference/object.html#properties
  121.         if (false === ($serializerContext[AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES] ?? true)) {
  122.             $definition['additionalProperties'] = false;
  123.         }
  124.         // see https://github.com/json-schema-org/json-schema-spec/pull/737
  125.         if (
  126.             Schema::VERSION_SWAGGER !== $version
  127.         ) {
  128.             if (($resourceMetadata instanceof ResourceMetadata
  129.                     && ($operationType && $operationName $resourceMetadata->getTypedOperationAttribute($operationType$operationName'deprecation_reason'nulltrue) : $resourceMetadata->getAttribute('deprecation_reason'null))
  130.             ) || ($operation && $operation->getDeprecationReason())
  131.             ) {
  132.                 $definition['deprecated'] = true;
  133.             }
  134.         }
  135.         // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
  136.         // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
  137.         if ($resourceMetadata instanceof ResourceMetadata && $resourceMetadata->getIri()) {
  138.             $definition['externalDocs'] = ['url' => $resourceMetadata->getIri()];
  139.         } elseif ($operation instanceof HttpOperation && ($operation->getTypes()[0] ?? null)) {
  140.             $definition['externalDocs'] = ['url' => $operation->getTypes()[0]];
  141.         }
  142.         // TODO: getFactoryOptions should be refactored because Item & Collection Operations don't exist anymore (API Platform 3.0)
  143.         $options $this->getFactoryOptions($serializerContext$validationGroups$operationType$operationName$operation instanceof HttpOperation $operation null);
  144.         foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass$options) as $propertyName) {
  145.             $propertyMetadata $this->propertyMetadataFactory->create($inputOrOutputClass$propertyName$options);
  146.             if (!$propertyMetadata->isReadable() && !$propertyMetadata->isWritable()) {
  147.                 continue;
  148.             }
  149.             $normalizedPropertyName $this->nameConverter $this->nameConverter->normalize($propertyName$inputOrOutputClass$format$serializerContext) : $propertyName;
  150.             if ($propertyMetadata->isRequired()) {
  151.                 $definition['required'][] = $normalizedPropertyName;
  152.             }
  153.             $this->buildPropertySchema($schema$definitionName$normalizedPropertyName$propertyMetadata$serializerContext$format);
  154.         }
  155.         return $schema;
  156.     }
  157.     private function buildPropertySchema(Schema $schemastring $definitionNamestring $normalizedPropertyName$propertyMetadata, array $serializerContextstring $format): void
  158.     {
  159.         $version $schema->getVersion();
  160.         $swagger Schema::VERSION_SWAGGER === $version;
  161.         $propertySchema $propertyMetadata->getSchema() ?? [];
  162.         if ($propertyMetadata instanceof ApiProperty) {
  163.             $additionalPropertySchema $propertyMetadata->getOpenapiContext() ?? [];
  164.         } else {
  165.             switch ($version) {
  166.                 case Schema::VERSION_SWAGGER:
  167.                     $basePropertySchemaAttribute 'swagger_context';
  168.                     break;
  169.                 case Schema::VERSION_OPENAPI:
  170.                     $basePropertySchemaAttribute 'openapi_context';
  171.                     break;
  172.                 default:
  173.                     $basePropertySchemaAttribute 'json_schema_context';
  174.             }
  175.             $additionalPropertySchema $propertyMetadata->getAttributes()[$basePropertySchemaAttribute] ?? [];
  176.         }
  177.         $propertySchema array_merge(
  178.             $propertySchema,
  179.             $additionalPropertySchema
  180.         );
  181.         if (false === $propertyMetadata->isWritable() && !$propertyMetadata->isInitializable()) {
  182.             $propertySchema['readOnly'] = true;
  183.         }
  184.         if (!$swagger && false === $propertyMetadata->isReadable()) {
  185.             $propertySchema['writeOnly'] = true;
  186.         }
  187.         if (null !== $description $propertyMetadata->getDescription()) {
  188.             $propertySchema['description'] = $description;
  189.         }
  190.         $deprecationReason $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getAttribute('deprecation_reason') : $propertyMetadata->getDeprecationReason();
  191.         // see https://github.com/json-schema-org/json-schema-spec/pull/737
  192.         if (!$swagger && null !== $deprecationReason) {
  193.             $propertySchema['deprecated'] = true;
  194.         }
  195.         // externalDocs is an OpenAPI specific extension, but JSON Schema allows additional keys, so we always add it
  196.         // See https://json-schema.org/latest/json-schema-core.html#rfc.section.6.4
  197.         $iri $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getIri() : $propertyMetadata->getTypes()[0] ?? null;
  198.         if (null !== $iri) {
  199.             $propertySchema['externalDocs'] = ['url' => $iri];
  200.         }
  201.         if (!isset($propertySchema['default']) && !empty($default $propertyMetadata->getDefault())) {
  202.             $propertySchema['default'] = $default;
  203.         }
  204.         if (!isset($propertySchema['example']) && !empty($example $propertyMetadata->getExample())) {
  205.             $propertySchema['example'] = $example;
  206.         }
  207.         if (!isset($propertySchema['example']) && isset($propertySchema['default'])) {
  208.             $propertySchema['example'] = $propertySchema['default'];
  209.         }
  210.         $valueSchema = [];
  211.         // TODO: 3.0 support multiple types, default value of types will be [] instead of null
  212.         $type $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getType() : $propertyMetadata->getBuiltinTypes()[0] ?? null;
  213.         if (null !== $type) {
  214.             if ($isCollection $type->isCollection()) {
  215.                 $keyType method_exists(Type::class, 'getCollectionKeyTypes') ? ($type->getCollectionKeyTypes()[0] ?? null) : $type->getCollectionKeyType();
  216.                 $valueType method_exists(Type::class, 'getCollectionValueTypes') ? ($type->getCollectionValueTypes()[0] ?? null) : $type->getCollectionValueType();
  217.             } else {
  218.                 $keyType null;
  219.                 $valueType $type;
  220.             }
  221.             if (null === $valueType) {
  222.                 $builtinType 'string';
  223.                 $className null;
  224.             } else {
  225.                 $builtinType $valueType->getBuiltinType();
  226.                 $className $valueType->getClassName();
  227.             }
  228.             $valueSchema $this->typeFactory->getType(new Type($builtinType$type->isNullable(), $className$isCollection$keyType$valueType), $format$propertyMetadata->isReadableLink(), $serializerContext$schema);
  229.         }
  230.         if (\array_key_exists('type'$propertySchema) && \array_key_exists('$ref'$valueSchema)) {
  231.             $propertySchema = new \ArrayObject($propertySchema);
  232.         } else {
  233.             $propertySchema = new \ArrayObject($propertySchema $valueSchema);
  234.         }
  235.         $schema->getDefinitions()[$definitionName]['properties'][$normalizedPropertyName] = $propertySchema;
  236.     }
  237.     private function buildDefinitionName(string $classNamestring $format 'json'string $inputOrOutputClass null$resourceMetadata null, array $serializerContext null): string
  238.     {
  239.         if ($resourceMetadata) {
  240.             $prefix $resourceMetadata instanceof ResourceMetadata $resourceMetadata->getShortName() : $resourceMetadata->getShortName();
  241.         }
  242.         if (!isset($prefix)) {
  243.             $prefix = (new \ReflectionClass($className))->getShortName();
  244.         }
  245.         if (null !== $inputOrOutputClass && $className !== $inputOrOutputClass) {
  246.             $parts explode('\\'$inputOrOutputClass);
  247.             $shortName end($parts);
  248.             $prefix .= '.'.$shortName;
  249.         }
  250.         if (isset($this->distinctFormats[$format])) {
  251.             // JSON is the default, and so isn't included in the definition name
  252.             $prefix .= '.'.$format;
  253.         }
  254.         $definitionName $serializerContext[OpenApiFactory::OPENAPI_DEFINITION_NAME] ?? $serializerContext[DocumentationNormalizer::SWAGGER_DEFINITION_NAME] ?? null;
  255.         if ($definitionName) {
  256.             $name sprintf('%s-%s'$prefix$definitionName);
  257.         } else {
  258.             $groups = (array) ($serializerContext[AbstractNormalizer::GROUPS] ?? []);
  259.             $name $groups sprintf('%s-%s'$prefiximplode('_'$groups)) : $prefix;
  260.         }
  261.         return $this->encodeDefinitionName($name);
  262.     }
  263.     private function encodeDefinitionName(string $name): string
  264.     {
  265.         return preg_replace('/[^a-zA-Z0-9.\-_]/''.'$name);
  266.     }
  267.     private function getMetadata(string $classNamestring $type Schema::TYPE_OUTPUTstring $operationType nullstring $operationName null, array $serializerContext null): ?array
  268.     {
  269.         if (!$this->isResourceClass($className)) {
  270.             return [
  271.                 null,
  272.                 $serializerContext ?? [],
  273.                 [],
  274.                 $className,
  275.             ];
  276.         }
  277.         /** @var ResourceMetadata|ResourceMetadataCollection $resourceMetadata */
  278.         $resourceMetadata $this->resourceMetadataFactory->create($className);
  279.         $attribute Schema::TYPE_OUTPUT === $type 'output' 'input';
  280.         $operation = ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) ? null $resourceMetadata->getOperation($operationName);
  281.         if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  282.             if (null === $operationType || null === $operationName) {
  283.                 $inputOrOutput $resourceMetadata->getAttribute($attribute, ['class' => $className]);
  284.             } else {
  285.                 $inputOrOutput $resourceMetadata->getTypedOperationAttribute($operationType$operationName$attribute, ['class' => $className], true);
  286.             }
  287.         } elseif ($operation) {
  288.             $inputOrOutput = (Schema::TYPE_OUTPUT === $type $operation->getOutput() : $operation->getInput()) ?? ['class' => $className];
  289.         } else {
  290.             $inputOrOutput = ['class' => $className];
  291.         }
  292.         if (null === ($inputOrOutput['class'] ?? $inputOrOutput->class ?? null)) {
  293.             // input or output disabled
  294.             return null;
  295.         }
  296.         return [
  297.             $resourceMetadata,
  298.             $serializerContext ?? $this->getSerializerContext($resourceMetadata$type$operationType$operationName),
  299.             $this->getValidationGroups($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface $resourceMetadata $operation$operationType$operationName),
  300.             $inputOrOutput['class'] ?? $inputOrOutput->class,
  301.         ];
  302.     }
  303.     private function getSerializerContext($resourceMetadatastring $type Schema::TYPE_OUTPUTstring $operationType nullstring $operationName null): array
  304.     {
  305.         if ($resourceMetadata instanceof ResourceMetadata) {
  306.             $attribute Schema::TYPE_OUTPUT === $type 'normalization_context' 'denormalization_context';
  307.         } else {
  308.             $operation $resourceMetadata->getOperation($operationName);
  309.         }
  310.         if (null === $operationType || null === $operationName) {
  311.             if ($resourceMetadata instanceof ResourceMetadata) {
  312.                 return $resourceMetadata->getAttribute($attribute, []);
  313.             }
  314.             return Schema::TYPE_OUTPUT === $type ? ($operation->getNormalizationContext() ?? []) : ($operation->getDenormalizationContext() ?? []);
  315.         }
  316.         if ($resourceMetadata instanceof ResourceMetadata) {
  317.             return $resourceMetadata->getTypedOperationAttribute($operationType$operationName$attribute, [], true);
  318.         }
  319.         return Schema::TYPE_OUTPUT === $type ? ($operation->getNormalizationContext() ?? []) : ($operation->getDenormalizationContext() ?? []);
  320.     }
  321.     /**
  322.      * @param HttpOperation|ResourceMetadata|null $resourceMetadata
  323.      */
  324.     private function getValidationGroups($resourceMetadata, ?string $operationType, ?string $operationName): array
  325.     {
  326.         if ($resourceMetadata instanceof ResourceMetadata) {
  327.             $attribute 'validation_groups';
  328.             if (null === $operationType || null === $operationName) {
  329.                 return \is_array($validationGroups $resourceMetadata->getAttribute($attribute, [])) ? $validationGroups : [];
  330.             }
  331.             return \is_array($validationGroups $resourceMetadata->getTypedOperationAttribute($operationType$operationName$attribute, [], true)) ? $validationGroups : [];
  332.         }
  333.         $groups $resourceMetadata ? ($resourceMetadata->getValidationContext()['groups'] ?? []) : [];
  334.         return \is_array($groups) ? $groups : [$groups];
  335.     }
  336.     /**
  337.      * Gets the options for the property name collection / property metadata factories.
  338.      */
  339.     private function getFactoryOptions(array $serializerContext, array $validationGroups, ?string $operationType, ?string $operationNameHttpOperation $operation null): array
  340.     {
  341.         $options = [
  342.             /* @see https://github.com/symfony/symfony/blob/v5.1.0/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php */
  343.             'enable_getter_setter_extraction' => true,
  344.         ];
  345.         if (isset($serializerContext[AbstractNormalizer::GROUPS])) {
  346.             /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
  347.             $options['serializer_groups'] = (array) $serializerContext[AbstractNormalizer::GROUPS];
  348.         }
  349.         if ($this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface && $operation) {
  350.             $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
  351.             $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
  352.         }
  353.         if (null !== $operationType && null !== $operationName) {
  354.             switch ($operationType) {
  355.                 case OperationType::COLLECTION:
  356.                     $options['collection_operation_name'] = $operationName;
  357.                     break;
  358.                 case OperationType::ITEM:
  359.                     $options['item_operation_name'] = $operationName;
  360.                     break;
  361.                 default:
  362.                     break;
  363.             }
  364.         }
  365.         if ($validationGroups) {
  366.             $options['validation_groups'] = $validationGroups;
  367.         }
  368.         return $options;
  369.     }
  370. }