Skip to content

feat(json-schema): mutualize json schema between formats #6960

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

Merged
merged 3 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1298,7 +1298,7 @@ jobs:
tests/Fixtures/app/console api:openapi:export --yaml -o build/out/openapi/openapi_v3.yaml
- name: Validate OpenAPI documents
run: |
npx @quobix/vacuum lint -r tests/Fixtures/app/ruleset.yaml build/out/openapi/openapi_v3.yaml -d
npx @quobix/vacuum lint -r tests/Fixtures/app/ruleset.yaml build/out/openapi/openapi_v3.yaml -d --ignore-array-circle-ref --ignore-polymorph-circle-ref -b --no-clip

laravel:
name: Laravel (PHP ${{ matrix.php }})
Expand Down
4 changes: 4 additions & 0 deletions features/jsonapi/related-resouces-inclusion.feature
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ Feature: JSON API Inclusion of Related Resources
}
"""

@createSchema
Scenario: Request inclusion of a non existing related resource
Given there are 3 dummy property objects
When I send a "GET" request to "/dummy_properties/1?include=foo"
Then the response status code should be 200
And the response should be in JSON
Expand Down Expand Up @@ -87,7 +89,9 @@ Feature: JSON API Inclusion of Related Resources
}
"""

@createSchema
Scenario: Request inclusion of a related resource keeping main object properties unfiltered
Given there are 3 dummy property objects
When I send a "GET" request to "/dummy_properties/1?include=group&fields[group]=id,foo&fields[DummyProperty]=bar,baz"
Then the response status code should be 200
And the response should be in JSON
Expand Down
111 changes: 2 additions & 109 deletions features/openapi/docs.feature
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,12 @@ Feature: Documentation support
And the JSON node "paths./api/custom-call/{id}.put" should exist
# Properties
And the "id" property exists for the OpenAPI class "Dummy"
And the "name" property is required for the OpenAPI class "Dummy"
And the "name" property is required for the OpenAPI class "Dummy.jsonld"
And the "genderType" property exists for the OpenAPI class "Person"
And the "genderType" property for the OpenAPI class "Person" should be equal to:
"""
{
"default": "male",
"example": "male",
"type": ["string", "null"],
"enum": [
"male",
Expand Down Expand Up @@ -153,10 +152,9 @@ Feature: Documentation support
And the JSON node "paths./related_dummies/{id}/related_to_dummy_friends.get.parameters" should have 6 elements

# Subcollection - check schema
And the JSON node "paths./related_dummies/{id}/related_to_dummy_friends.get.responses.200.content.application/ld+json.schema.properties.hydra:member.items.$ref" should be equal to "#/components/schemas/RelatedToDummyFriend.jsonld-fakemanytomany"
And the JSON node "paths./related_dummies/{id}/related_to_dummy_friends.get.responses.200.content.application/ld+json.schema.allOf[1].properties.hydra:member.items.$ref" should be equal to "#/components/schemas/RelatedToDummyFriend.jsonld-fakemanytomany"

# Deprecations
And the JSON node "paths./dummies.get.deprecated" should be false
And the JSON node "paths./deprecated_resources.get.deprecated" should be true
And the JSON node "paths./deprecated_resources.post.deprecated" should be true
And the JSON node "paths./deprecated_resources/{id}.get.deprecated" should be true
Expand All @@ -166,111 +164,6 @@ Feature: Documentation support

# Formats
And the OpenAPI class "Dummy.jsonld" exists
And the "@id" property exists for the OpenAPI class "Dummy.jsonld"
And the JSON node "paths./dummies.get.responses.200.content.application/ld+json" should be equal to:
"""
{
"schema": {
"type": "object",
"properties": {
"hydra:member": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Dummy.jsonld"
}
},
"hydra:totalItems": {
"type": "integer",
"minimum": 0
},
"hydra:view": {
"type": "object",
"properties": {
"@id": {
"type": "string",
"format": "iri-reference"
},
"@type": {
"type": "string"
},
"hydra:first": {
"type": "string",
"format": "iri-reference"
},
"hydra:last": {
"type": "string",
"format": "iri-reference"
},
"hydra:previous": {
"type": "string",
"format": "iri-reference"
},
"hydra:next": {
"type": "string",
"format": "iri-reference"
}
},
"example": {
"@id": "string",
"type": "string",
"hydra:first": "string",
"hydra:last": "string",
"hydra:previous": "string",
"hydra:next": "string"
}
},
"hydra:search": {
"type": "object",
"properties": {
"@type": {
"type": "string"
},
"hydra:template": {
"type": "string"
},
"hydra:variableRepresentation": {
"type": "string"
},
"hydra:mapping": {
"type": "array",
"items": {
"type": "object",
"properties": {
"@type": {
"type": "string"
},
"variable": {
"type": "string"
},
"property": {
"type": ["string", "null"]
},
"required": {
"type": "boolean"
}
}
}
}
}
}
},
"required": [
"hydra:member"
]
}
}
"""
And the JSON node "paths./dummies.get.responses.200.content.application/json" should be equal to:
"""
{
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Dummy"
}
}
}
"""
And the JSON node "paths./override_open_api_responses.post.responses" should be equal to:
"""
{
Expand Down
170 changes: 118 additions & 52 deletions src/Hal/JsonSchema/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@

namespace ApiPlatform\Hal\JsonSchema;

use ApiPlatform\JsonSchema\DefinitionNameFactory;
use ApiPlatform\JsonSchema\DefinitionNameFactoryInterface;
use ApiPlatform\JsonSchema\ResourceMetadataTrait;
use ApiPlatform\JsonSchema\Schema;
use ApiPlatform\JsonSchema\SchemaFactoryAwareInterface;
use ApiPlatform\JsonSchema\SchemaFactoryInterface;
use ApiPlatform\JsonSchema\SchemaUriPrefixTrait;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;

/**
* Decorator factory which adds HAL properties to the JSON Schema document.
Expand All @@ -26,6 +31,11 @@
*/
final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareInterface
{
use ResourceMetadataTrait;
use SchemaUriPrefixTrait;

private const COLLECTION_BASE_SCHEMA_NAME = 'HalCollectionBaseSchema';

private const HREF_PROP = [
'href' => [
'type' => 'string',
Expand All @@ -44,8 +54,12 @@ final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareI
],
];

public function __construct(private readonly SchemaFactoryInterface $schemaFactory)
public function __construct(private readonly SchemaFactoryInterface $schemaFactory, private ?DefinitionNameFactoryInterface $definitionNameFactory = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null)
{
if (!$definitionNameFactory) {
$this->definitionNameFactory = new DefinitionNameFactory();
}
$this->resourceMetadataFactory = $resourceMetadataFactory;
if ($this->schemaFactory instanceof SchemaFactoryAwareInterface) {
$this->schemaFactory->setSchemaFactory($this);
}
Expand All @@ -56,79 +70,131 @@ public function __construct(private readonly SchemaFactoryInterface $schemaFacto
*/
public function buildSchema(string $className, string $format = 'jsonhal', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema
{
$schema = $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
if ('jsonhal' !== $format) {
return $schema;
return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
}

if (!$this->isResourceClass($className)) {
$operation = null;
$inputOrOutputClass = null;
$serializerContext ??= [];
} else {
$operation = $this->findOperation($className, $type, $operation, $serializerContext, $format);
$inputOrOutputClass = $this->findOutputClass($className, $type, $operation, $serializerContext);
$serializerContext ??= $this->getSerializerContext($operation, $type);
}

if (null === $inputOrOutputClass) {
// input or output disabled
return $this->schemaFactory->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);
}

$schema = $this->schemaFactory->buildSchema($className, 'json', $type, $operation, $schema, $serializerContext, $forceCollection);
$definitions = $schema->getDefinitions();
if ($key = $schema->getRootDefinitionKey()) {
$definitions[$key]['properties'] = self::BASE_PROPS + ($definitions[$key]['properties'] ?? []);
$definitionName = $this->definitionNameFactory->create($className, $format, $className, $operation, $serializerContext);
$prefix = $this->getSchemaUriPrefix($schema->getVersion());
$collectionKey = $schema->getItemsDefinitionKey();

// Already computed
if (!$collectionKey && isset($definitions[$definitionName])) {
$schema['$ref'] = $prefix.$definitionName;

return $schema;
}
if ($key = $schema->getItemsDefinitionKey()) {
$definitions[$key]['properties'] = self::BASE_PROPS + ($definitions[$key]['properties'] ?? []);

$key = $schema->getRootDefinitionKey() ?? $collectionKey;

$definitions[$definitionName] = [
'allOf' => [
['type' => 'object', 'properties' => self::BASE_PROPS],
['$ref' => $prefix.$key],
],
];

if (isset($definitions[$key]['description'])) {
$definitions[$definitionName]['description'] = $definitions[$key]['description'];
}

if (!$collectionKey) {
$schema['$ref'] = $prefix.$definitionName;

return $schema;
}

if (($schema['type'] ?? '') === 'array') {
$items = $schema['items'];
unset($schema['items']);

$schema['type'] = 'object';
$schema['properties'] = [
'_embedded' => [
'anyOf' => [
[
if (!isset($definitions[self::COLLECTION_BASE_SCHEMA_NAME])) {
$definitions[self::COLLECTION_BASE_SCHEMA_NAME] = [
'type' => 'object',
'properties' => [
'_embedded' => [
'anyOf' => [
[
'type' => 'object',
'properties' => [
'item' => [
'type' => 'array',
],
],
],
['type' => 'object'],
],
],
'totalItems' => [
'type' => 'integer',
'minimum' => 0,
],
'itemsPerPage' => [
'type' => 'integer',
'minimum' => 0,
],
'_links' => [
'type' => 'object',
'properties' => [
'item' => [
'type' => 'array',
'items' => $items,
'self' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'first' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'last' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'next' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'previous' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
],
],
['type' => 'object'],
],
],
'totalItems' => [
'type' => 'integer',
'minimum' => 0,
],
'itemsPerPage' => [
'type' => 'integer',
'minimum' => 0,
],
'_links' => [
'required' => ['_links', '_embedded'],
];
}

unset($schema['items']);
unset($schema['type']);

$schema['description'] = "$definitionName collection.";
$schema['allOf'] = [
['$ref' => $prefix.self::COLLECTION_BASE_SCHEMA_NAME],
[
'type' => 'object',
'properties' => [
'self' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'first' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'last' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'next' => [
'type' => 'object',
'properties' => self::HREF_PROP,
],
'previous' => [
'type' => 'object',
'properties' => self::HREF_PROP,
'_embedded' => [
'additionalProperties' => [
'type' => 'array',
'items' => ['$ref' => $prefix.$definitionName],
],
],
],
],
];
$schema['required'] = [
'_links',
'_embedded',
];

return $schema;
}
Expand Down
Loading
Loading