Skip to content
Draft
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
8 changes: 6 additions & 2 deletions src/JsonLd/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
use ApiPlatform\Metadata\ResourceAwareInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
Expand Down Expand Up @@ -91,8 +92,11 @@ public function normalize(mixed $data, ?string $format = null, array $context =
$isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass);
if ($isResourceClass && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
$resourceClass = $this->resourceClassResolver->getResourceClass($data, $previousResourceClass);
if (isset($context['operation']) && $context['operation'] instanceof HttpOperation && $context['operation']->getClass() !== $resourceClass) {
$context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(null, false, true);
if (
($data instanceof ResourceAwareInterface && !isset($context['operation']))
|| (isset($context['operation']) && $context['operation'] instanceof HttpOperation && $context['operation']->getClass() !== $resourceClass)
) {
$context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperationForObject($data, false, true);
}
$context = $this->initContext($resourceClass, $context);
$metadata = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
Expand Down
8 changes: 6 additions & 2 deletions src/JsonSchema/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public function buildSchema(string $className, string $format = 'json', string $
$definition['externalDocs'] = ['url' => $operation->getTypes()[0]];
}

$options = ['schema_type' => $type] + $this->getFactoryOptions($serializerContext, $validationGroups);
$options = ['schema_type' => $type] + $this->getFactoryOptions($serializerContext, $validationGroups, $operation);
foreach ($this->propertyNameCollectionFactory->create($inputOrOutputClass, $options) as $propertyName) {
$propertyMetadata = $this->propertyMetadataFactory->create($inputOrOutputClass, $propertyName, $options);

Expand Down Expand Up @@ -387,7 +387,7 @@ private function getValidationGroups(Operation $operation): array
/**
* Gets the options for the property name collection / property metadata factories.
*/
private function getFactoryOptions(array $serializerContext, array $validationGroups): array
private function getFactoryOptions(array $serializerContext, array $validationGroups, ?Operation $operation = null): array
{
$options = [
/* @see https://github.com/symfony/symfony/blob/v5.1.0/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php */
Expand All @@ -403,6 +403,10 @@ private function getFactoryOptions(array $serializerContext, array $validationGr
$options['serializer_attributes'] = (array) $serializerContext[AbstractNormalizer::ATTRIBUTES];
}

if ($operationName = $operation?->getName()) {
$options['operation_name'] = $operationName;
}

if ($validationGroups) {
$options['validation_groups'] = $validationGroups;
}
Expand Down
15 changes: 15 additions & 0 deletions src/Metadata/Resource/ResourceMetadataCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\ResourceAwareInterface;
use ApiPlatform\Metadata\Util\UriTemplateHelper;

/**
Expand All @@ -36,6 +37,20 @@ public function __construct(private readonly string $resourceClass, array $input
parent::__construct($input);
}

public function getOperationForObject(object $object, bool $forceCollection = false, bool $httpOperation = false): Operation
{
if ($object instanceof ResourceAwareInterface) {
$shortName = $object->getResource();
foreach ($this as $resource) {
if ($shortName === $resource->getShortName()) {
return (new self($this->resourceClass, [$resource]))->getOperation(null, $forceCollection, $httpOperation);
}
}
}

return $this->getOperation(null, $forceCollection, $httpOperation);
}

public function getOperation(?string $operationName = null, bool $forceCollection = false, bool $httpOperation = false, bool $forceGraphQl = false): Operation
{
$operationName ??= '';
Expand Down
19 changes: 19 additions & 0 deletions src/Metadata/ResourceAwareInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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\Metadata;

interface ResourceAwareInterface
{
public function getResource(): string;
}
19 changes: 16 additions & 3 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
use ApiPlatform\Metadata\ResourceAwareInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
Expand Down Expand Up @@ -172,6 +173,10 @@ public function normalize(mixed $data, ?string $format = null, array $context =
$context = $this->initContext($resourceClass, $context);
}

if ($data instanceof ResourceAwareInterface && !isset($context['operation']) && $this->resourceMetadataCollectionFactory && $this->resourceClassResolver->isResourceClass($resourceClass)) {
$context['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperationForObject($data, false, true);
}

$context['api_normalize'] = true;
$iri = $context['iri'] ??= $this->iriConverter->getIriFromResource($data, UrlGeneratorInterface::ABS_URL, $context['operation'] ?? null, $context);

Expand Down Expand Up @@ -813,19 +818,27 @@ protected function getFactoryOptions(array $context): array
$options['serializer_groups'] = (array) $context[self::GROUPS];
}

$operationCacheKey = ($context['resource_class'] ?? '').($context['operation_name'] ?? '').($context['root_operation_name'] ?? '');
$operationName = ($context['operation'] ?? null)?->getName() ?? $context['operation_name'] ?? null;
$rootOperationName = $context['root_operation_name'] ?? $operationName;

$operationCacheKey = ($context['resource_class'] ?? '').$operationName.$rootOperationName;
$suffix = ($context['api_normalize'] ?? '') ? 'n' : '';
if ($operationCacheKey && isset($this->localFactoryOptionsCache[$operationCacheKey.$suffix])) {
return $options + $this->localFactoryOptionsCache[$operationCacheKey.$suffix];
}

// This is a hot spot
if (isset($context['resource_class'])) {
if (null !== $operationName) {
$options['operation_name'] = $operationName;
$options['root_operation_name'] = $rootOperationName;
}

// Note that the groups need to be read on the root operation
if ($operation = ($context['root_operation'] ?? null)) {
$options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
$options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
$options['operation_name'] = $operation->getName();
$options['root_operation_name'] = $operation->getName();
}
}

Expand Down Expand Up @@ -995,7 +1008,7 @@ protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata,
$objResourceClass = $this->resourceClassResolver->getResourceClass($obj, $resourceClass);
$context['resource_class'] = $objResourceClass;
if ($this->resourceMetadataCollectionFactory) {
$context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperation();
$context['operation'] = $this->resourceMetadataCollectionFactory->create($objResourceClass)->getOperationForObject($obj);
}

$value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
Expand Down
2 changes: 1 addition & 1 deletion src/Serializer/Tests/AbstractItemNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2207,7 +2207,7 @@ public function testCacheKey(): void

$operationCacheKey = (new \ReflectionClass($normalizer))->getProperty('localFactoryOptionsCache')->getValue($normalizer);
$this->assertEquals(array_keys($operationCacheKey), [\sprintf('%s%s%s%s', Dummy::class, 'operation_name', 'root_operation_name', 'n')]);
$this->assertEquals(current($operationCacheKey), ['serializer_groups' => ['group'], 'api_allow_update' => false]);
$this->assertEquals(current($operationCacheKey), ['serializer_groups' => ['group'], 'api_allow_update' => false, 'operation_name' => 'operation_name', 'root_operation_name' => 'root_operation_name']);
}

public function testSupportsDenormalizationWithApiPlatformInputContext(): void
Expand Down
6 changes: 4 additions & 2 deletions src/Symfony/Routing/IriConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Operation\Factory\OperationMetadataFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\ResourceAwareInterface;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\UriVariablesConverterInterface;
use ApiPlatform\Metadata\UrlGeneratorInterface;
Expand Down Expand Up @@ -148,7 +149,7 @@ public function getIriFromResource(object|string $resource, int $referenceType =

// item_uri_template steers both the skolem check and the resource class promotion below,
// so it has to be part of the key even when it did not resolve to an operation.
$localOperationCacheKey = ($operation?->getName() ?? '').$resourceClass.(\is_string($resource) ? '_s' : '_o').($operation instanceof CollectionOperationInterface ? '_c' : '_i').($context['item_uri_template'] ?? '');
$localOperationCacheKey = ($operation?->getName() ?? '').$resourceClass.($resource instanceof ResourceAwareInterface ? '@'.$resource->getResource() : '').(\is_string($resource) ? '_s' : '_o').($operation instanceof CollectionOperationInterface ? '_c' : '_i').($context['item_uri_template'] ?? '');
if ($operation && isset($this->localOperationCache[$localOperationCacheKey])) {
return $this->generateSymfonyRoute($resource, $referenceType, $this->localOperationCache[$localOperationCacheKey], $context, $this->localIdentifiersExtractorOperationCache[$localOperationCacheKey] ?? null);
}
Expand Down Expand Up @@ -186,7 +187,8 @@ public function getIriFromResource(object|string $resource, int $referenceType =
} else {
$forceCollection = $operation instanceof CollectionOperationInterface;
try {
$operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation(null, $forceCollection, true);
$resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
$operation = \is_object($resource) ? $resourceMetadataCollection->getOperationForObject($resource, $forceCollection, true) : $resourceMetadataCollection->getOperation(null, $forceCollection, true);
$identifiersExtractorOperation = $operation;
} catch (OperationNotFoundException) {
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?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\DynamicResource;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\Exception\PropertyNotFoundException;
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;

final class DynamicPropertyMetadataFactory implements PropertyMetadataFactoryInterface
{
public function __construct(
private readonly PropertyMetadataFactoryInterface $decorated,
private readonly \Closure $resourceMetadataCollectionFactory,
) {
}

public function create(string $resourceClass, string $property, array $options = []): ApiProperty
{
if (DynamicRecord::class !== $resourceClass) {
return $this->decorated->create($resourceClass, $property, $options);
}

$resource = DynamicResourceDefinitions::resourceForOperation(($this->resourceMetadataCollectionFactory)(), $options['operation_name'] ?? null);

return DynamicResourceDefinitions::properties($resource)[$property] ?? throw new PropertyNotFoundException(\sprintf('Property "%s" of "%s" not found.', $property, $resource ?? DynamicRecord::class));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?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\DynamicResource;

use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Metadata\Property\PropertyNameCollection;

final class DynamicPropertyNameCollectionFactory implements PropertyNameCollectionFactoryInterface
{
public function __construct(
private readonly PropertyNameCollectionFactoryInterface $decorated,
private readonly \Closure $resourceMetadataCollectionFactory,
) {
}

public function create(string $resourceClass, array $options = []): PropertyNameCollection
{
if (DynamicRecord::class !== $resourceClass) {
return $this->decorated->create($resourceClass, $options);
}

$resource = DynamicResourceDefinitions::resourceForOperation(($this->resourceMetadataCollectionFactory)(), $options['operation_name'] ?? null);

return new PropertyNameCollection(array_keys(DynamicResourceDefinitions::properties($resource)));
}
}
46 changes: 46 additions & 0 deletions tests/Fixtures/TestBundle/DynamicResource/DynamicRecord.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?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\DynamicResource;

use ApiPlatform\Metadata\ResourceAwareInterface;

final class DynamicRecord implements ResourceAwareInterface
{
/**
* @param array<string, mixed> $data
*/
public function __construct(private readonly string $resource, private array $data = [])
{
}

public function getResource(): string
{
return $this->resource;
}

public function __get(string $name): mixed
{
return $this->data[$name] ?? null;
}

public function __set(string $name, mixed $value): void
{
$this->data[$name] = $value;
}

public function __isset(string $name): bool
{
return isset($this->data[$name]);
}
}
Loading
Loading