Skip to content

chore(HttpCache): outsource cache tag collection into normalizer events #5753

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

Closed
wants to merge 1 commit into from
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
46 changes: 46 additions & 0 deletions src/HttpCache/EventListener/NormalizerListener.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 <[email protected]>
*
* 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\HttpCache\EventListener;

use ApiPlatform\Serializer\NormalizeItemEvent;

/**
* Collects cache tags during normalization.
*
* @author Urban Suppiger <[email protected]>
*/
class NormalizerListener
{
public function onPreNormalizeItem(NormalizeItemEvent $event): void
{
$this->addResourceToContext($event);
}

public function onNormalizeRelation(NormalizeItemEvent $event): void
{
$this->addResourceToContext($event);
}

public function onJsonApiNormalizeRelation(NormalizeItemEvent $event): void
{
$this->addResourceToContext($event);
}

private function addResourceToContext(NormalizeItemEvent $event): void
{
if (isset($event->context['resources'])) {
$event->context['resources'][$event->iri] = $event->iri;
}
}
}
19 changes: 12 additions & 7 deletions src/JsonApi/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
use ApiPlatform\Serializer\AbstractItemNormalizer;
use ApiPlatform\Serializer\CacheKeyTrait;
use ApiPlatform\Serializer\ContextTrait;
use ApiPlatform\Serializer\NormalizeItemEvent;
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
Expand All @@ -52,9 +54,9 @@ final class ItemNormalizer extends AbstractItemNormalizer

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)
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 ?EventDispatcher $eventDispatcher = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker);
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $eventDispatcher);
}

/**
Expand Down Expand Up @@ -222,10 +224,6 @@ protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $rel
if (null !== $relatedObject) {
$iri = $this->iriConverter->getIriFromResource($relatedObject);
$context['iri'] = $iri;

if (isset($context['resources'])) {
$context['resources'][$iri] = $iri;
}
}

if (null === $relatedObject || isset($context['api_included'])) {
Expand All @@ -241,12 +239,19 @@ protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $rel
return $normalizedRelatedObject;
}

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

if ($this->eventDispatcher) {
$event = new NormalizeItemEvent($relatedObject, $format, $context, $iri, $data);
$this->eventDispatcher->dispatch($event, NormalizeItemEvent::JSONAPI_NORMALIZE_RELATION);
}

return $data;
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/JsonLd/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use ApiPlatform\Serializer\AbstractItemNormalizer;
use ApiPlatform\Serializer\ContextTrait;
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
Expand All @@ -45,9 +46,9 @@ final class ItemNormalizer extends AbstractItemNormalizer

public const FORMAT = 'jsonld';

public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, private readonly ContextBuilderInterface $contextBuilder, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ResourceAccessCheckerInterface $resourceAccessChecker = null)
public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, private readonly ContextBuilderInterface $contextBuilder, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?EventDispatcher $eventDispatcher = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker);
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $eventDispatcher);
}

/**
Expand Down
35 changes: 28 additions & 7 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Util\CloneTrait;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
Expand Down Expand Up @@ -61,7 +62,7 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
protected array $localCache = [];
protected array $localFactoryOptionsCache = [];

public function __construct(protected PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, protected PropertyMetadataFactoryInterface $propertyMetadataFactory, protected IriConverterInterface $iriConverter, protected ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, protected ?ResourceAccessCheckerInterface $resourceAccessChecker = null)
public function __construct(protected PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, protected PropertyMetadataFactoryInterface $propertyMetadataFactory, protected IriConverterInterface $iriConverter, protected ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, protected ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?EventDispatcher $eventDispatcher = null)
{
if (!isset($defaultContext['circular_reference_handler'])) {
$defaultContext['circular_reference_handler'] = fn ($object): ?string => $this->iriConverter->getIriFromResource($object);
Expand Down Expand Up @@ -160,12 +161,18 @@ public function normalize(mixed $object, string $format = null, array $context =
$emptyResourceAsIri = $context['api_empty_resource_as_iri'] ?? false;
unset($context['api_empty_resource_as_iri']);

if (isset($context['resources'])) {
$context['resources'][$iri] = $iri;
if ($this->eventDispatcher) {
$event = new NormalizeItemEvent($object, $format, $context, $iri, null);
$this->eventDispatcher->dispatch($event, NormalizeItemEvent::NORMALIZE_ITEM_PRE);
}

$data = parent::normalize($object, $format, $context);

if ($this->eventDispatcher) {
$event = new NormalizeItemEvent($object, $format, $context, $iri, $data);
$this->eventDispatcher->dispatch($event, NormalizeItemEvent::NORMALIZE_ITEM_POST);
}

if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
return $iri;
}
Expand Down Expand Up @@ -635,7 +642,14 @@ protected function getAttributeValue(object $object, string $attribute, string $
$resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
$childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);

return $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
$data = $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);

if ($this->eventDispatcher) {
$event = new NormalizeAttributeEvent($object, $format, $context, $context['iri'], $data, $attribute, $propertyMetadata, $type, $childContext);
$this->eventDispatcher->dispatch($event, NormalizeAttributeEvent::NORMALIZE_ATTRIBUTE);
}

return $data;
}

if (
Expand All @@ -650,7 +664,13 @@ protected function getAttributeValue(object $object, string $attribute, string $
$resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
$childContext = $this->createChildContext($this->createOperationContext($context, $resourceClass), $attribute, $format);

return $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
$data = $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
if ($this->eventDispatcher) {
$event = new NormalizeAttributeEvent($object, $format, $context, $context['iri'], $data, $attribute, $propertyMetadata, $type, $childContext);
$this->eventDispatcher->dispatch($event, NormalizeAttributeEvent::NORMALIZE_ATTRIBUTE);
}

return $data;
}

if (!$this->serializer instanceof NormalizerInterface) {
Expand Down Expand Up @@ -728,8 +748,9 @@ protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $rel

$iri = $this->iriConverter->getIriFromResource($relatedObject);

if (isset($context['resources'])) {
$context['resources'][$iri] = $iri;
if ($this->eventDispatcher) {
$event = new NormalizeItemEvent($relatedObject, $format, $context, $iri, $iri);
$this->eventDispatcher->dispatch($event, NormalizeItemEvent::NORMALIZE_RELATION);
}

$push = $propertyMetadata->getPush() ?? false;
Expand Down
5 changes: 3 additions & 2 deletions src/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
Expand All @@ -38,9 +39,9 @@ class ItemNormalizer extends AbstractItemNormalizer
{
private readonly LoggerInterface $logger;

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, LoggerInterface $logger = null, ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ResourceAccessCheckerInterface $resourceAccessChecker = null, array $defaultContext = [])
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, LoggerInterface $logger = null, ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ResourceAccessCheckerInterface $resourceAccessChecker = null, array $defaultContext = [], protected ?EventDispatcher $eventDispatcher = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker);
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker, $eventDispatcher);

$this->logger = $logger ?: new NullLogger();
}
Expand Down
41 changes: 41 additions & 0 deletions src/Serializer/NormalizeAttributeEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Serializer;

use ApiPlatform\Metadata\ApiProperty;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Contracts\EventDispatcher\Event;

/**
* Event class for normalizer events (normalize attributes).
*
* @author Urban Suppiger <[email protected]>
*/
class NormalizeAttributeEvent extends Event
{
public const NORMALIZE_ATTRIBUTE = 'api_platform.normalizer.normalize_attribute';

public function __construct(
public mixed $object,
public ?string $format = null,
public array $context = [],
public ?string $iri = null,
public array|string|int|float|bool|\ArrayObject|null $data = null,
public ?string $attribute = null,
public ?ApiProperty $propertyMetadata = null,
public ?Type $type = null,
public array $childContext = [],
) {
}
}
38 changes: 38 additions & 0 deletions src/Serializer/NormalizeItemEvent.php
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 <[email protected]>
*
* 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\Serializer;

use Symfony\Contracts\EventDispatcher\Event;

/**
* Event class for normalizer events (normalize items).
*
* @author Urban Suppiger <[email protected]>
*/
class NormalizeItemEvent extends Event
{
public const NORMALIZE_ITEM_PRE = 'api_platform.normalizer.normalize_item.pre';
public const NORMALIZE_ITEM_POST = 'api_platform.normalizer.normalize_item.post';
public const NORMALIZE_RELATION = 'api_platform.normalizer.normalize_relation';
public const JSONAPI_NORMALIZE_RELATION = 'api_platform.jsonapi.normalizer.normalize_relation';

public function __construct(
public mixed $object,
public ?string $format = null,
public array $context = [],
public ?string $iri = null,
public array|string|int|float|bool|\ArrayObject|null $data = null
) {
}
}
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@
<argument>null</argument>
<argument type="service" id="api_platform.metadata.resource.metadata_collection_factory" on-invalid="ignore" />
<argument type="service" id="api_platform.security.resource_access_checker" on-invalid="ignore" />
<argument type="collection" />
<argument type="service" id="event_dispatcher" on-invalid="ignore" />

<!-- Run before serializer.normalizer.json_serializable -->
<tag name="serializer.normalizer" priority="-895" />
Expand Down
7 changes: 7 additions & 0 deletions src/Symfony/Bundle/Resources/config/http_cache_purger.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,12 @@
<argument type="service" id="api_platform.http_cache.purger" on-invalid="null" />
<tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" priority="-2" />
</service>

<service id="api_platform.http_cache.listener.normalizer.collect_tags" class="ApiPlatform\HttpCache\EventListener\NormalizerListener">
<tag name="kernel.event_listener" event="api_platform.normalizer.normalize_item.pre" method="onPreNormalizeItem" />
<tag name="kernel.event_listener" event="api_platform.normalizer.normalize_relation" method="onNormalizeRelation" />
<tag name="kernel.event_listener" event="api_platform.jsonapi.normalizer.normalize_relation" method="onJsonApiNormalizeRelation" />
</service>

</services>
</container>
1 change: 1 addition & 0 deletions src/Symfony/Bundle/Resources/config/jsonapi.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<argument type="collection" />
<argument type="service" id="api_platform.metadata.resource.metadata_collection_factory" />
<argument type="service" id="api_platform.security.resource_access_checker" on-invalid="ignore" />
<argument type="service" id="event_dispatcher" on-invalid="ignore" />

<!-- Run before serializer.normalizer.json_serializable -->
<tag name="serializer.normalizer" priority="-890" />
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/Resources/config/jsonld.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<argument type="service" id="serializer.mapping.class_metadata_factory" on-invalid="ignore" />
<argument type="collection" />
<argument type="service" id="api_platform.security.resource_access_checker" on-invalid="ignore" />
<argument type="service" id="event_dispatcher" on-invalid="ignore" />

<!-- Run before serializer.normalizer.json_serializable -->
<tag name="serializer.normalizer" priority="-890" />
Expand Down
Loading