Skip to content
Open
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
90 changes: 82 additions & 8 deletions src/JsonApi/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
Expand All @@ -28,6 +29,7 @@
use ApiPlatform\Serializer\CacheKeyTrait;
use ApiPlatform\Serializer\ContextTrait;
use ApiPlatform\Serializer\TagCollectorInterface;
use ApiPlatform\State\ProviderInterface;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
Expand Down Expand Up @@ -59,9 +61,25 @@

private array $componentsCache = [];

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null)
public function __construct(
PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
PropertyMetadataFactoryInterface $propertyMetadataFactory,
IriConverterInterface $iriConverter,
ResourceClassResolverInterface $resourceClassResolver,
?PropertyAccessorInterface $propertyAccessor = null,
?NameConverterInterface $nameConverter = null,
?ClassMetadataFactoryInterface $classMetadataFactory = null,
array $defaultContext = [],
?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null,
?ResourceAccessCheckerInterface $resourceAccessChecker = null,
protected ?TagCollectorInterface $tagCollector = null,
private readonly IdentifiersExtractorInterface $identifiersExtractor,

Check failure on line 76 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Deprecated in PHP 8.1: Required parameter $identifiersExtractor follows optional parameter $tagCollector.
private readonly ProviderInterface $provider,

Check failure on line 77 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Deprecated in PHP 8.0: Required parameter $provider follows optional parameter $tagCollector.
bool $useIriAsId = true
)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
$this->useIriAsId = $useIriAsId;

Check failure on line 82 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Access to an undefined property ApiPlatform\JsonApi\Serializer\ItemNormalizer::$useIriAsId.
}

/**
Expand Down Expand Up @@ -125,8 +143,14 @@

$includedResourcesData = $this->getRelatedResources($object, $format, $context, $allRelationshipsData);

$id = $context['iri'];
if (!$this->useIriAsId) {

Check failure on line 147 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Access to an undefined property ApiPlatform\JsonApi\Serializer\ItemNormalizer::$useIriAsId.
$identifiers = $this->identifiersExtractor->getIdentifiersFromItem($object);
$id = (string) array_values($identifiers)[0];
}

$resourceData = [
'id' => $context['iri'],
'id' => $id,
'type' => $this->getResourceShortName($resourceClass),
];

Expand Down Expand Up @@ -174,10 +198,21 @@
throw new NotNormalizableValueException('Update is not allowed for this operation.');
}

$context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri(
$data['data']['id'],
$context + ['fetch_data' => false]
);
$context += ['fetch_data' => false];
if ($this->useIriAsId) {

Check failure on line 202 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Access to an undefined property ApiPlatform\JsonApi\Serializer\ItemNormalizer::$useIriAsId.
$context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri(
$data['data']['id'],
$context
);
} else {
$operation = $context['operation'] ?? $context['api_platform_operation'] ?? null;
$uriVariables = $context['uriVariables'] ?? [];
$context[self::OBJECT_TO_POPULATE] = $this->provider->provide(
$operation,
$uriVariables,
$context
);
}
}

// Merge attributes and relationships, into format expected by the parent normalizer
Expand Down Expand Up @@ -225,7 +260,41 @@
}

try {
return $this->iriConverter->getResourceFromIri($value['id'], $context + ['fetch_data' => true]);
$context += ['fetch_data' => true];
if ($this->useIriAsId) {

Check failure on line 264 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Access to an undefined property ApiPlatform\JsonApi\Serializer\ItemNormalizer::$useIriAsId.
return $this->iriConverter->getResourceFromIri($value['id'], $context);
} else {
$targetClass = $propertyMetadata->getBuiltinTypes()[0]->getClassName();
$resourceMetadata = $this->resourceMetadataCollectionFactory
->create($targetClass);

$getOperation = null;
foreach ($resourceMetadata as $resource) {
foreach ($resource->getOperations() as $operation) {
if ($operation instanceof Get) {

Check failure on line 274 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Class ApiPlatform\JsonApi\Serializer\Get not found.
$getOperation = $operation;
break 2;
}
}
}
if (null === $getOperation) {
throw new ItemNotFoundException(sprintf(
'No GET operation found for resource "%s".',
$targetClass
));
}

$uriVariablesDefinition = $getOperation->getUriVariables();

Check failure on line 287 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Call to method getUriVariables() on an unknown class ApiPlatform\JsonApi\Serializer\Get.

$uriVariables = [];
foreach ($uriVariablesDefinition as $varName => $link) {
foreach ($link->getIdentifiers() as $identifier) {
$uriVariables[$identifier] = (string) $value['data']['id'];
}
}
return $this->provider->provide($getOperation, $uriVariables, $context);
}

} catch (ItemNotFoundException $e) {
if (!isset($context['not_normalizable_value_exceptions'])) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
Expand Down Expand Up @@ -273,10 +342,15 @@
return $normalizedRelatedObject;
}

$id = $iri;
if (!$this->useIriAsId) {

Check failure on line 346 in src/JsonApi/Serializer/ItemNormalizer.php

View workflow job for this annotation

GitHub Actions / PHPStan (PHP 8.4)

Access to an undefined property ApiPlatform\JsonApi\Serializer\ItemNormalizer::$useIriAsId.
$identifiers = $this->identifiersExtractor->getIdentifiersFromItem($relatedObject);
$id = (string) array_values($identifiers)[0];
}
$context['data'] = [
'data' => [
'id' => $id,
'type' => $this->getResourceShortName($resourceClass),
'id' => $iri,
],
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public function load(array $configs, ContainerBuilder $container): void
$this->registerOAuthConfiguration($container, $config);
$this->registerOpenApiConfiguration($container, $config, $loader);
$this->registerSwaggerConfiguration($container, $config, $loader);
$this->registerJsonApiConfiguration($formats, $loader, $config);
$this->registerJsonApiConfiguration($container, $formats, $loader, $config);
$this->registerJsonLdHydraConfiguration($container, $formats, $loader, $config);
$this->registerJsonHalConfiguration($formats, $loader);
$this->registerJsonProblemConfiguration($errorFormats, $loader);
Expand Down Expand Up @@ -630,7 +630,7 @@ private function registerSwaggerConfiguration(ContainerBuilder $container, array
$container->setParameter('api_platform.swagger_ui.extra_configuration', $config['openapi']['swagger_ui_extra_configuration'] ?: $config['swagger']['swagger_ui_extra_configuration']);
}

private function registerJsonApiConfiguration(array $formats, PhpFileLoader $loader, array $config): void
private function registerJsonApiConfiguration(ContainerBuilder $container, array $formats, PhpFileLoader $loader, array $config): void
{
if (!isset($formats['jsonapi'])) {
return;
Expand All @@ -642,6 +642,9 @@ private function registerJsonApiConfiguration(array $formats, PhpFileLoader $loa

$loader->load('jsonapi.php');
$loader->load('state/jsonapi.php');

$container->getDefinition('api_platform.jsonapi.normalizer.item')
->addArgument($config['jsonapi']['use_iri_as_id']);
}

private function registerJsonLdHydraConfiguration(ContainerBuilder $container, array $formats, PhpFileLoader $loader, array $config): void
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Bundle/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,16 @@ public function getConfigTreeBuilder(): TreeBuilder
->end()
->end()
->end()
->arrayNode('jsonapi')
->setDeprecated('api-platform/core', '5.0')
->addDefaultsIfNotSet()
->children()
->booleanNode('use_iri_as_id')
->setDeprecated('api-platform/core', '5.0', 'Using IRI in JSON:API output will be no longer supported and replaced by "type" + "id".')
->defaultTrue()
->end()
->end()
->end()
->arrayNode('eager_loading')
->canBeDisabled()
->addDefaultsIfNotSet()
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/Resources/config/jsonapi.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@
service('api_platform.metadata.resource.metadata_collection_factory'),
service('api_platform.security.resource_access_checker')->ignoreOnInvalid(),
service('api_platform.http_cache.tag_collector')->ignoreOnInvalid(),
service('api_platform.api.identifiers_extractor'),
service('api_platform.state_provider'),
])
->tag('serializer.normalizer', ['priority' => -890]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,9 @@ private function runDefaultConfigTests(array $doctrineIntegrationsToLoad = ['orm
'hydra_prefix' => null,
],
'enable_phpdoc_parser' => true,
'jsonapi' => [
'use_iri_as_id' => true
],
], $config);
}

Expand Down
Loading