Skip to content
Closed
Show file tree
Hide file tree
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: 44 additions & 1 deletion src/JsonSchema/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\Util\TypeHelper;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\TypeInfo\Type;
Expand Down Expand Up @@ -51,7 +53,7 @@ final class SchemaFactory implements SchemaFactoryInterface, SchemaFactoryAwareI
public const OPENAPI_DEFINITION_NAME = 'openapi_definition_name';
public const PARTIAL_UPDATE = 'partial_update';

public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ?NameConverterInterface $nameConverter = null, ?ResourceClassResolverInterface $resourceClassResolver = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null)
public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory, private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory, private readonly ?NameConverterInterface $nameConverter = null, ?ResourceClassResolverInterface $resourceClassResolver = null, private ?DefinitionNameFactoryInterface $definitionNameFactory = null, private readonly ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null)
{
if (!$definitionNameFactory) {
$this->definitionNameFactory = new DefinitionNameFactory();
Expand Down Expand Up @@ -129,6 +131,12 @@ public function buildSchema(string $className, string $format = 'json', string $
return $schema;
}

if (Schema::VERSION_SWAGGER !== $version && ($mapping = $this->classDiscriminatorResolver?->getMappingForClass($inputOrOutputClass)) && null === $mapping->getMappedObjectType($inputOrOutputClass)) {
$this->buildDiscriminatorDefinition($schema, $definitionName, $mapping, $format, $type, $serializerContext);

return $schema;
}

/** @var \ArrayObject<string, mixed> $definition */
$definition = new \ArrayObject(['type' => 'object']);
$definitions[$definitionName] = $definition;
Expand Down Expand Up @@ -172,9 +180,44 @@ public function buildSchema(string $className, string $format = 'json', string $
$this->buildPropertySchema($schema, $definitionName, $normalizedPropertyName, $propertyMetadata, $serializerContext, $format, $type);
}

if (($mapping = $this->classDiscriminatorResolver?->getMappingForMappedObject($inputOrOutputClass)) && null !== $typeValue = $mapping->getMappedObjectType($inputOrOutputClass)) {
$typeProperty = $mapping->getTypeProperty();
$definition['properties'][$typeProperty] = new \ArrayObject(['type' => 'string', 'enum' => [$typeValue]]);
if (!$isPartialUpdate && !\in_array($typeProperty, $definition['required'] ?? [], true)) {
$definition['required'][] = $typeProperty;
}
}

return $schema;
}

private function buildDiscriminatorDefinition(Schema $schema, string $definitionName, ClassDiscriminatorMapping $mapping, string $format, string $type, array $serializerContext): void
{
$version = $schema->getVersion();
$definitions = $schema->getDefinitions();
/** @var \ArrayObject<string, mixed> $definition */
$definition = new \ArrayObject(['oneOf' => []]);
// registered before recursing so that a subclass referencing its parent does not loop
$definitions[$definitionName] = $definition;

$oneOf = $refs = [];
foreach ($mapping->getTypesMapping() as $typeValue => $mappedClass) {
$subSchema = new Schema($version);
$subSchema->setDefinitions($definitions);
$result = ($this->schemaFactory ?: $this)->buildSchema($mappedClass, $format, $type, null, $subSchema, $serializerContext + [self::FORCE_SUBSCHEMA => true]);

if (isset($result['$ref'])) {
$oneOf[] = ['$ref' => $result['$ref']];
$refs[$typeValue] = $result['$ref'];
}
}

$definition['oneOf'] = $oneOf;
if (Schema::VERSION_OPENAPI === $version) {
$definition['discriminator'] = ['propertyName' => $mapping->getTypeProperty(), 'mapping' => $refs];
}
}

private function buildPropertySchema(Schema $schema, string $definitionName, string $normalizedPropertyName, ApiProperty $propertyMetadata, array $serializerContext, string $format, string $parentType): void
{
$version = $schema->getVersion();
Expand Down
2 changes: 2 additions & 0 deletions src/Laravel/ApiPlatformProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
Expand Down Expand Up @@ -970,6 +971,7 @@ public function register(): void
$app->make(NameConverterInterface::class),
$app->make(ResourceClassResolverInterface::class),
$app->make(DefinitionNameFactoryInterface::class),
new ClassDiscriminatorFromClassMetadata($app->make(ClassMetadataFactoryInterface::class)),
);
});
$this->app->singleton(JsonApiSchemaFactory::class, static function (Application $app) {
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/Resources/config/json_schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
service('api_platform.name_converter')->ignoreOnInvalid(),
service('api_platform.resource_class_resolver'),
service('api_platform.json_schema.definition_name_factory')->ignoreOnInvalid(),
service('serializer.mapping.class_discriminator_resolver')->ignoreOnInvalid(),
]);

$services->alias(SchemaFactoryInterface::class, 'api_platform.json_schema.schema_factory');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction;

final class ArchiveBookAction extends BookAction
{
public function __construct(
public readonly string $reason,
) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction;

use Symfony\Component\Serializer\Attribute\DiscriminatorMap;

#[DiscriminatorMap(typeProperty: 'action', mapping: [
'archive' => ArchiveBookAction::class,
'merge' => MergeBookAction::class,
])]
abstract class BookAction
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;

#[ApiResource(
operations: [
new Post(
uriTemplate: '/discriminated_book_actions',
input: BookAction::class,
processor: [self::class, 'process'],
),
]
)]
final class BookActionResource
{
public ?int $id = 1;

public ?string $performed = null;

public static function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): self
{
$resource = new self();
$resource->performed = $data::class;

return $resource;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction;

final class MergeBookAction extends BookAction
{
/**
* @param list<string> $sources
*/
public function __construct(
public readonly string $target,
public readonly array $sources = [],
) {
}
}
96 changes: 96 additions & 0 deletions tests/Functional/DiscriminatorMapOpenApiTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Tests\Functional;

use ApiPlatform\Test\ApiTestCase;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction\BookAction;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction\BookActionResource;
use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\DiscriminatedBookAction\MergeBookAction;
use ApiPlatform\Tests\SetupClassResourcesTrait;

final class DiscriminatorMapOpenApiTest extends ApiTestCase
{
use SetupClassResourcesTrait;

protected static ?bool $alwaysBootKernel = false;

/**
* @return class-string[]
*/
public static function getResources(): array
{
return [BookActionResource::class];
}

public function testDiscriminatedInputIsDocumentedAsOneOf(): void
{
$response = self::createClient()->request('GET', '/docs', [
'headers' => ['Accept' => 'application/vnd.openapi+json'],
]);
$this->assertResponseIsSuccessful();

$json = $response->toArray();
$schemas = $json['components']['schemas'];

$requestSchema = $json['paths']['/discriminated_book_actions']['post']['requestBody']['content']['application/ld+json']['schema'];
$this->assertSame(['$ref' => '#/components/schemas/BookActionResource.BookAction'], $requestSchema);

$this->assertSame([
'oneOf' => [
['$ref' => '#/components/schemas/ArchiveBookAction'],
['$ref' => '#/components/schemas/MergeBookAction'],
],
'discriminator' => [
'propertyName' => 'action',
'mapping' => [
'archive' => '#/components/schemas/ArchiveBookAction',
'merge' => '#/components/schemas/MergeBookAction',
],
],
], $schemas['BookActionResource.BookAction']);

$archive = $schemas['ArchiveBookAction'];
$this->assertSame(['type' => 'string', 'enum' => ['archive']], $archive['properties']['action']);
$this->assertSame(['type' => 'string'], $archive['properties']['reason']);
$this->assertSame(['action'], $archive['required']);

$merge = $schemas['MergeBookAction'];
$this->assertSame(['type' => 'string', 'enum' => ['merge']], $merge['properties']['action']);
$this->assertArrayHasKey('sources', $merge['properties']);
$this->assertSame(['action'], $merge['required']);
}

public function testDiscriminatorIsOpenApiOnly(): void
{
$schema = self::getContainer()->get('api_platform.json_schema.schema_factory')->buildSchema(BookAction::class, 'json', 'input');
$definition = $schema->getDefinitions()['BookAction'];

$this->assertSame([
['$ref' => '#/definitions/ArchiveBookAction'],
['$ref' => '#/definitions/MergeBookAction'],
], $definition['oneOf']);
$this->assertArrayNotHasKey('discriminator', $definition);
}

public function testDiscriminatedInputIsDenormalized(): void
{
self::createClient()->request('POST', '/discriminated_book_actions', [
'headers' => ['Content-Type' => 'application/ld+json'],
'json' => ['action' => 'merge', 'target' => '/books/1', 'sources' => ['/books/2']],
]);

$this->assertResponseStatusCodeSame(201);
$this->assertJsonContains(['performed' => MergeBookAction::class]);
}
}
Loading