diff --git a/src/HttpCache/PurgeTagProviderInterface.php b/src/HttpCache/PurgeTagProviderInterface.php new file mode 100644 index 00000000000..973d2932ef7 --- /dev/null +++ b/src/HttpCache/PurgeTagProviderInterface.php @@ -0,0 +1,30 @@ + + * + * 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; + +use ApiPlatform\Metadata\Operation; + +/** + * Collects extra HTTP cache tags to invalidate for a given resource. + */ +interface PurgeTagProviderInterface +{ + /** + * @param object $resource the persisted object (the entity or document when the operation declares stateOptions), or the object about to be removed on a delete operation + * @param array $context $context['previous_data'] holds the API resource as read before the request, null on creation + * + * @return iterable + */ + public function getTags(object $resource, Operation $operation, array $context = []): iterable; +} diff --git a/src/HttpCache/State/PurgeTagsProcessor.php b/src/HttpCache/State/PurgeTagsProcessor.php new file mode 100644 index 00000000000..b91b93edce7 --- /dev/null +++ b/src/HttpCache/State/PurgeTagsProcessor.php @@ -0,0 +1,72 @@ + + * + * 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\State; + +use ApiPlatform\HttpCache\PurgerInterface; +use ApiPlatform\HttpCache\PurgeTagProviderInterface; +use ApiPlatform\Metadata\DeleteOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\State\ProcessorInterface; + +final class PurgeTagsProcessor implements ProcessorInterface +{ + /** + * @param iterable $providers + */ + public function __construct( + private readonly ProcessorInterface $decorated, + private readonly PurgerInterface $purger, + private readonly iterable $providers = [], + ) { + } + + public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed + { + $tags = []; + $collectBefore = $operation instanceof DeleteOperationInterface && \is_object($data); + + if ($collectBefore) { + $tags = $this->collect($data, $operation, $context); + } + + $result = $this->decorated->process($data, $operation, $uriVariables, $context); + + if (!$collectBefore && \is_object($result)) { + $tags = $this->collect($result, $operation, $context); + } + + if ($tags) { + $this->purger->purge(array_values($tags)); + } + + return $result; + } + + /** + * @param array $context + * + * @return array + */ + private function collect(object $resource, Operation $operation, array $context): array + { + $tags = []; + foreach ($this->providers as $provider) { + foreach ($provider->getTags($resource, $operation, $context) as $tag) { + $tags[$tag] = $tag; + } + } + + return $tags; + } +} diff --git a/src/HttpCache/Tests/State/PurgeTagsProcessorTest.php b/src/HttpCache/Tests/State/PurgeTagsProcessorTest.php new file mode 100644 index 00000000000..d93dcbfa2ef --- /dev/null +++ b/src/HttpCache/Tests/State/PurgeTagsProcessorTest.php @@ -0,0 +1,119 @@ + + * + * 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\Tests\State; + +use ApiPlatform\HttpCache\PurgerInterface; +use ApiPlatform\HttpCache\PurgeTagProviderInterface; +use ApiPlatform\HttpCache\State\PurgeTagsProcessor; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Put; +use ApiPlatform\State\ProcessorInterface; +use PHPUnit\Framework\TestCase; + +class PurgeTagsProcessorTest extends TestCase +{ + public function testDeleteCollectsTagsBeforeTheDecoratedProcessor(): void + { + $resource = new \stdClass(); + $calls = []; + + $decorated = $this->createMock(ProcessorInterface::class); + $decorated->expects($this->once())->method('process')->willReturnCallback(static function () use (&$calls) { + $calls[] = 'process'; + + return null; + }); + + $provider = $this->createMock(PurgeTagProviderInterface::class); + $provider->expects($this->once())->method('getTags')->with($resource, $this->isInstanceOf(Delete::class))->willReturnCallback(static function () use (&$calls) { + $calls[] = 'getTags'; + + return ['/parents/1/children']; + }); + + $purger = $this->createMock(PurgerInterface::class); + $purger->expects($this->once())->method('purge')->with(['/parents/1/children']); + + (new PurgeTagsProcessor($decorated, $purger, [$provider]))->process($resource, new Delete(), [], []); + + $this->assertSame(['getTags', 'process'], $calls); + } + + public function testNonDeleteCollectsTagsFromTheDecoratedResult(): void + { + $data = new \stdClass(); + $result = new \stdClass(); + $previousData = new \stdClass(); + $context = ['previous_data' => $previousData]; + + $decorated = $this->createStub(ProcessorInterface::class); + $decorated->method('process')->willReturn($result); + + $provider = $this->createMock(PurgeTagProviderInterface::class); + $provider->expects($this->once())->method('getTags')->with($result, $this->isInstanceOf(Put::class), $context)->willReturn(['/parents/1/children', '/parents/2/children']); + + $purger = $this->createMock(PurgerInterface::class); + $purger->expects($this->once())->method('purge')->with(['/parents/1/children', '/parents/2/children']); + + $this->assertSame($result, (new PurgeTagsProcessor($decorated, $purger, [$provider]))->process($data, new Put(), [], $context)); + } + + public function testTagsAreDeduplicatedAcrossProviders(): void + { + $resource = new \stdClass(); + + $decorated = $this->createStub(ProcessorInterface::class); + $decorated->method('process')->willReturn($resource); + + $first = $this->createStub(PurgeTagProviderInterface::class); + $first->method('getTags')->willReturn(['/a', '/b']); + $second = $this->createStub(PurgeTagProviderInterface::class); + $second->method('getTags')->willReturn(['/b', '/c']); + + $purger = $this->createMock(PurgerInterface::class); + $purger->expects($this->once())->method('purge')->with(['/a', '/b', '/c']); + + (new PurgeTagsProcessor($decorated, $purger, [$first, $second]))->process($resource, new Put(), [], []); + } + + public function testNoPurgeWithoutTags(): void + { + $resource = new \stdClass(); + + $decorated = $this->createStub(ProcessorInterface::class); + $decorated->method('process')->willReturn($resource); + + $provider = $this->createStub(PurgeTagProviderInterface::class); + $provider->method('getTags')->willReturn([]); + + $purger = $this->createMock(PurgerInterface::class); + $purger->expects($this->never())->method('purge'); + + (new PurgeTagsProcessor($decorated, $purger, [$provider]))->process($resource, new Put(), [], []); + } + + public function testNonObjectResultDoesNotCallProviders(): void + { + $decorated = $this->createStub(ProcessorInterface::class); + $decorated->method('process')->willReturn(null); + + $provider = $this->createMock(PurgeTagProviderInterface::class); + $provider->expects($this->never())->method('getTags'); + + $purger = $this->createMock(PurgerInterface::class); + $purger->expects($this->never())->method('purge'); + + (new PurgeTagsProcessor($decorated, $purger, [$provider]))->process(new \stdClass(), new Put(), [], []); + } +} diff --git a/src/Laravel/ApiPlatformDeferredProvider.php b/src/Laravel/ApiPlatformDeferredProvider.php index 9cfeee62516..0735b23ab91 100644 --- a/src/Laravel/ApiPlatformDeferredProvider.php +++ b/src/Laravel/ApiPlatformDeferredProvider.php @@ -20,6 +20,9 @@ use ApiPlatform\GraphQl\Type\FieldsBuilderEnumInterface; use ApiPlatform\GraphQl\Type\TypeConverterInterface; use ApiPlatform\GraphQl\Type\TypesContainerInterface; +use ApiPlatform\HttpCache\PurgerInterface; +use ApiPlatform\HttpCache\PurgeTagProviderInterface; +use ApiPlatform\HttpCache\State\PurgeTagsProcessor; use ApiPlatform\JsonApi\Filter\SparseFieldset; use ApiPlatform\JsonApi\Filter\SparseFieldsetParameterProvider; use ApiPlatform\Laravel\Controller\ApiPlatformController; @@ -195,11 +198,24 @@ public function register(): void $tagged['api_platform.swagger_ui.processor'] = $app->make(SwaggerUiProcessor::class); } + if (interface_exists(PurgerInterface::class) && $app->bound(PurgerInterface::class)) { + $purger = $app->make(PurgerInterface::class); + foreach ($tagged as $processor) { + if ($processor instanceof PersistProcessor || $processor instanceof RemoveProcessor) { + $tagged[$processor::class] = new PurgeTagsProcessor($processor, $purger, $app->tagged(PurgeTagProviderInterface::class)); + } + } + } + return new CallableProcessor(new ServiceLocator($tagged)); }); $this->autoconfigure($classes, ProcessorInterface::class, [RemoveProcessor::class, PersistProcessor::class]); + if (interface_exists(PurgeTagProviderInterface::class)) { + $this->autoconfigure($classes, PurgeTagProviderInterface::class, []); + } + $this->app->singleton(CallableProvider::class, static function (Application $app) { $tagged = iterator_to_array($app->tagged(ProviderInterface::class)); diff --git a/src/Laravel/Tests/MockPurgeTagProvider.php b/src/Laravel/Tests/MockPurgeTagProvider.php new file mode 100644 index 00000000000..caf02578810 --- /dev/null +++ b/src/Laravel/Tests/MockPurgeTagProvider.php @@ -0,0 +1,30 @@ + + * + * 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\Laravel\Tests; + +use ApiPlatform\HttpCache\PurgeTagProviderInterface; +use ApiPlatform\Metadata\DeleteOperationInterface; +use ApiPlatform\Metadata\Operation; + +class MockPurgeTagProvider implements PurgeTagProviderInterface +{ + public function getTags(object $resource, Operation $operation, array $context = []): iterable + { + if ($operation instanceof DeleteOperationInterface) { + return ['provider_delete']; + } + + return \is_object($context['previous_data'] ?? null) ? ['provider_update'] : ['provider_insert']; + } +} diff --git a/src/Laravel/Tests/PurgeTagProviderTest.php b/src/Laravel/Tests/PurgeTagProviderTest.php new file mode 100644 index 00000000000..c80552e9437 --- /dev/null +++ b/src/Laravel/Tests/PurgeTagProviderTest.php @@ -0,0 +1,104 @@ + + * + * 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\Laravel\Tests; + +use ApiPlatform\HttpCache\PurgeTagProviderInterface; +use ApiPlatform\Laravel\Test\ApiTestAssertionsTrait; +use Illuminate\Foundation\Testing\RefreshDatabase; +use Orchestra\Testbench\Concerns\WithWorkbench; +use Orchestra\Testbench\TestCase; +use Workbench\App\Models\Author; +use Workbench\App\Models\Book; +use Workbench\App\Purger\MockPurger; +use Workbench\Database\Factories\AuthorFactory; +use Workbench\Database\Factories\BookFactory; + +class PurgeTagProviderTest extends TestCase +{ + use ApiTestAssertionsTrait; + use RefreshDatabase; + use WithWorkbench; + + protected function getEnvironmentSetUp($app): void + { + $app['config']->set('api-platform.http_cache.invalidation.purger', MockPurger::class); + $app->tag([MockPurgeTagProvider::class], PurgeTagProviderInterface::class); + } + + protected function setUp(): void + { + parent::setUp(); + MockPurger::reset(); + } + + public function testProviderTagsOnCreate(): void + { + AuthorFactory::new()->create(); + $author = Author::first(); + + $r = $this->postJson('/api/books', [ + 'isbn' => '9783161484100', + 'name' => 'The Test Book', + 'author' => '/api/authors/'.$author->id, + ], ['Accept' => 'application/ld+json', 'content-type' => 'application/ld+json']); + + $this->assertTagsWerePurged([ + $r->json()['@id'], + '/api/books', + 'provider_insert', + ]); + } + + public function testProviderTagsOnUpdate(): void + { + BookFactory::new()->has(AuthorFactory::new())->create(); + $book = Book::first(); + + $this->patchJson('/api/books/'.$book->id, [ + 'name' => 'An Updated Name', + ], [ + 'Accept' => 'application/ld+json', + 'Content-Type' => 'application/merge-patch+json', + ]); + + $this->assertTagsWerePurged([ + '/api/books', + '/api/books/'.$book->id, + 'provider_update', + ]); + } + + public function testProviderTagsOnDelete(): void + { + BookFactory::new()->has(AuthorFactory::new())->create(); + $book = Book::first(); + + $this->delete('/api/books/'.$book->id, headers: ['accept' => 'application/ld+json']); + + $this->assertTagsWerePurged([ + '/api/books', + '/api/books/'.$book->id, + 'provider_delete', + ]); + } + + /** + * @param string[] $expectedTags + */ + private function assertTagsWerePurged(array $expectedTags): void + { + sort($expectedTags); + $this->assertEquals($expectedTags, MockPurger::getPurgedTags()); + } +} diff --git a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php index 52531dfb23f..56772b97979 100644 --- a/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php +++ b/src/Symfony/Bundle/DependencyInjection/ApiPlatformExtension.php @@ -31,6 +31,7 @@ use ApiPlatform\GraphQl\Resolver\QueryItemResolverInterface; use ApiPlatform\GraphQl\Type\Definition\TypeInterface as GraphQlTypeInterface; use ApiPlatform\HttpCache\PurgerInterface; +use ApiPlatform\HttpCache\PurgeTagProviderInterface; use ApiPlatform\JsonApi\Serializer\ItemNormalizer as JsonApiItemNormalizer; use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\AsOperationMutator; @@ -233,6 +234,8 @@ public function load(array $configs, ContainerBuilder $container): void ->addTag('api_platform.uri_variables.transformer'); $container->registerForAutoconfiguration(ParameterProviderInterface::class) ->addTag('api_platform.parameter_provider'); + $container->registerForAutoconfiguration(PurgeTagProviderInterface::class) + ->addTag('api_platform.http_cache.purge_tag_provider'); $container->registerAttributeForAutoconfiguration( AsResourceMutator::class, diff --git a/src/Symfony/Bundle/Resources/config/doctrine_odm_http_cache_purger.php b/src/Symfony/Bundle/Resources/config/doctrine_odm_http_cache_purger.php index e4a64b24ea8..d84d67f1006 100644 --- a/src/Symfony/Bundle/Resources/config/doctrine_odm_http_cache_purger.php +++ b/src/Symfony/Bundle/Resources/config/doctrine_odm_http_cache_purger.php @@ -13,6 +13,7 @@ namespace Symfony\Component\DependencyInjection\Loader\Configurator; +use ApiPlatform\HttpCache\State\PurgeTagsProcessor; use ApiPlatform\Symfony\Doctrine\EventListener\PurgeHttpCacheListener; return static function (ContainerConfigurator $container) { @@ -30,4 +31,20 @@ ]) ->tag('doctrine_mongodb.odm.event_listener', ['event' => 'onFlush']) ->tag('doctrine_mongodb.odm.event_listener', ['event' => 'postFlush']); + + $services->set('api_platform.doctrine_mongodb.odm.http_cache.purge_tags.persist_processor', PurgeTagsProcessor::class) + ->decorate('api_platform.doctrine_mongodb.odm.state.persist_processor') + ->args([ + service('api_platform.doctrine_mongodb.odm.http_cache.purge_tags.persist_processor.inner'), + service('api_platform.http_cache.purger'), + tagged_iterator('api_platform.http_cache.purge_tag_provider'), + ]); + + $services->set('api_platform.doctrine_mongodb.odm.http_cache.purge_tags.remove_processor', PurgeTagsProcessor::class) + ->decorate('api_platform.doctrine_mongodb.odm.state.remove_processor') + ->args([ + service('api_platform.doctrine_mongodb.odm.http_cache.purge_tags.remove_processor.inner'), + service('api_platform.http_cache.purger'), + tagged_iterator('api_platform.http_cache.purge_tag_provider'), + ]); }; diff --git a/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php b/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php index a01a9cc7028..0f177f96b32 100644 --- a/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php +++ b/src/Symfony/Bundle/Resources/config/doctrine_orm_http_cache_purger.php @@ -13,6 +13,7 @@ namespace Symfony\Component\DependencyInjection\Loader\Configurator; +use ApiPlatform\HttpCache\State\PurgeTagsProcessor; use ApiPlatform\Symfony\Doctrine\EventListener\PurgeHttpCacheListener; return static function (ContainerConfigurator $container) { @@ -32,4 +33,20 @@ ->tag('doctrine.event_listener', ['event' => 'onFlush']) ->tag('doctrine.event_listener', ['event' => 'postFlush']) ->tag('kernel.reset', ['method' => 'reset', 'on_invalid' => 'ignore']); + + $services->set('api_platform.doctrine.orm.http_cache.purge_tags.persist_processor', PurgeTagsProcessor::class) + ->decorate('api_platform.doctrine.orm.state.persist_processor') + ->args([ + service('api_platform.doctrine.orm.http_cache.purge_tags.persist_processor.inner'), + service('api_platform.http_cache.purger'), + tagged_iterator('api_platform.http_cache.purge_tag_provider'), + ]); + + $services->set('api_platform.doctrine.orm.http_cache.purge_tags.remove_processor', PurgeTagsProcessor::class) + ->decorate('api_platform.doctrine.orm.state.remove_processor') + ->args([ + service('api_platform.doctrine.orm.http_cache.purge_tags.remove_processor.inner'), + service('api_platform.http_cache.purger'), + tagged_iterator('api_platform.http_cache.purge_tag_provider'), + ]); }; diff --git a/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php b/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php index 494a70e770d..01b34d353e3 100644 --- a/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php +++ b/src/Symfony/Tests/Bundle/DependencyInjection/ApiPlatformExtensionTest.php @@ -653,4 +653,28 @@ public function testHttpCachePurgeListenerRegisteredForMongoDbOdmWhenInvalidatio $tags = $this->container->getDefinition('api_platform.doctrine_mongodb.odm.listener.http_cache.purge')->getTags(); $this->assertSame([['event' => 'onFlush'], ['event' => 'postFlush']], $tags['doctrine_mongodb.odm.event_listener']); } + + public function testPurgeTagsProcessorsDecorateDoctrineOrmProcessorsWhenInvalidationEnabled(): void + { + $config = self::DEFAULT_CONFIG; + $config['api_platform']['http_cache']['invalidation']['enabled'] = true; + $config['api_platform']['doctrine']['enabled'] = true; + (new ApiPlatformExtension())->load($config, $this->container); + + $this->assertSame('api_platform.doctrine.orm.state.persist_processor', $this->container->getDefinition('api_platform.doctrine.orm.http_cache.purge_tags.persist_processor')->getDecoratedService()[0]); + $this->assertSame('api_platform.doctrine.orm.state.remove_processor', $this->container->getDefinition('api_platform.doctrine.orm.http_cache.purge_tags.remove_processor')->getDecoratedService()[0]); + } + + public function testPurgeTagsProcessorsDecorateMongoDbOdmProcessorsWhenInvalidationEnabled(): void + { + $config = self::DEFAULT_CONFIG; + $config['api_platform']['http_cache']['invalidation']['enabled'] = true; + $config['api_platform']['doctrine']['enabled'] = false; + $config['api_platform']['doctrine_mongodb_odm']['enabled'] = true; + (new ApiPlatformExtension())->load($config, $this->container); + + $this->assertSame('api_platform.doctrine_mongodb.odm.state.persist_processor', $this->container->getDefinition('api_platform.doctrine_mongodb.odm.http_cache.purge_tags.persist_processor')->getDecoratedService()[0]); + $this->assertSame('api_platform.doctrine_mongodb.odm.state.remove_processor', $this->container->getDefinition('api_platform.doctrine_mongodb.odm.http_cache.purge_tags.remove_processor')->getDecoratedService()[0]); + $this->assertNotContainerHasService('api_platform.doctrine.orm.http_cache.purge_tags.persist_processor'); + } } diff --git a/tests/Fixtures/TestBundle/ApiResource/MappedDeliveryDay.php b/tests/Fixtures/TestBundle/ApiResource/MappedDeliveryDay.php new file mode 100644 index 00000000000..de9141ba8ed --- /dev/null +++ b/tests/Fixtures/TestBundle/ApiResource/MappedDeliveryDay.php @@ -0,0 +1,34 @@ + + * + * 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; + +use ApiPlatform\Doctrine\Orm\State\Options; +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\Put; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DeliveryDay; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[ApiResource( + operations: [new Get(), new Put()], + stateOptions: new Options(entityClass: DeliveryDay::class), +)] +#[Map(target: DeliveryDay::class)] +final class MappedDeliveryDay +{ + #[Map(if: false)] + public ?int $id = null; + + public string $day; +} diff --git a/tests/Fixtures/TestBundle/Document/DeliveryDay.php b/tests/Fixtures/TestBundle/Document/DeliveryDay.php new file mode 100644 index 00000000000..db2063c4927 --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/DeliveryDay.php @@ -0,0 +1,50 @@ + + * + * 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\Document; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Link; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +#[ApiResource( + operations: [ + new Post(), + new Get(), + new GetCollection( + uriTemplate: '/suppliers/{supplierId}/delivery_days', + uriVariables: [ + 'supplierId' => new Link(fromProperty: 'deliveryDays', fromClass: Supplier::class), + ], + ), + new Put(), + new Delete(), + ], +)] +#[ODM\Document] +class DeliveryDay +{ + #[ODM\Id(strategy: 'INCREMENT', type: 'int')] + public ?int $id = null; + + #[ODM\ReferenceOne(targetDocument: Supplier::class, inversedBy: 'deliveryDays', storeAs: 'id')] + public ?Supplier $supplier = null; + + #[ODM\Field] + public string $day = ''; +} diff --git a/tests/Fixtures/TestBundle/Document/Supplier.php b/tests/Fixtures/TestBundle/Document/Supplier.php new file mode 100644 index 00000000000..cde900842da --- /dev/null +++ b/tests/Fixtures/TestBundle/Document/Supplier.php @@ -0,0 +1,40 @@ + + * + * 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\Document; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; +use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; + +#[ApiResource(operations: [new Get()])] +#[ODM\Document] +class Supplier +{ + #[ODM\Id(strategy: 'INCREMENT', type: 'int')] + public ?int $id = null; + + #[ODM\Field] + public string $name = ''; + + /** @var Collection */ + #[ODM\ReferenceMany(targetDocument: DeliveryDay::class, mappedBy: 'supplier')] + public Collection $deliveryDays; + + public function __construct() + { + $this->deliveryDays = new ArrayCollection(); + } +} diff --git a/tests/Fixtures/TestBundle/Entity/DeliveryDay.php b/tests/Fixtures/TestBundle/Entity/DeliveryDay.php new file mode 100644 index 00000000000..be177490080 --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/DeliveryDay.php @@ -0,0 +1,55 @@ + + * + * 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\Entity; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Delete; +use ApiPlatform\Metadata\Get; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\Link; +use ApiPlatform\Metadata\Post; +use ApiPlatform\Metadata\Put; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedDeliveryDay; +use Doctrine\ORM\Mapping as ORM; +use Symfony\Component\ObjectMapper\Attribute\Map; + +#[ApiResource( + operations: [ + new Post(), + new Get(), + new GetCollection( + uriTemplate: '/suppliers/{supplierId}/delivery_days', + uriVariables: [ + 'supplierId' => new Link(fromProperty: 'deliveryDays', fromClass: Supplier::class), + ], + ), + new Put(), + new Delete(), + ], +)] +#[ORM\Entity] +#[Map(target: MappedDeliveryDay::class)] +class DeliveryDay +{ + #[ORM\Column(type: 'integer')] + #[ORM\Id] + #[ORM\GeneratedValue] + public ?int $id = null; + + #[ORM\ManyToOne(inversedBy: 'deliveryDays')] + public ?Supplier $supplier = null; + + #[ORM\Column] + public string $day = ''; +} diff --git a/tests/Fixtures/TestBundle/Entity/Supplier.php b/tests/Fixtures/TestBundle/Entity/Supplier.php new file mode 100644 index 00000000000..dc545c3af6e --- /dev/null +++ b/tests/Fixtures/TestBundle/Entity/Supplier.php @@ -0,0 +1,42 @@ + + * + * 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\Entity; + +use ApiPlatform\Metadata\ApiResource; +use ApiPlatform\Metadata\Get; +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; +use Doctrine\ORM\Mapping as ORM; + +#[ApiResource(operations: [new Get()])] +#[ORM\Entity] +class Supplier +{ + #[ORM\Column(type: 'integer')] + #[ORM\Id] + #[ORM\GeneratedValue] + public ?int $id = null; + + #[ORM\Column] + public string $name = ''; + + /** @var Collection */ + #[ORM\OneToMany(targetEntity: DeliveryDay::class, mappedBy: 'supplier')] + public Collection $deliveryDays; + + public function __construct() + { + $this->deliveryDays = new ArrayCollection(); + } +} diff --git a/tests/Fixtures/TestBundle/HttpCache/DeliveryDayPurgeTagProvider.php b/tests/Fixtures/TestBundle/HttpCache/DeliveryDayPurgeTagProvider.php new file mode 100644 index 00000000000..c6a7858f6ee --- /dev/null +++ b/tests/Fixtures/TestBundle/HttpCache/DeliveryDayPurgeTagProvider.php @@ -0,0 +1,55 @@ + + * + * 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\HttpCache; + +use ApiPlatform\HttpCache\PurgeTagProviderInterface; +use ApiPlatform\Metadata\DeleteOperationInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedDeliveryDay; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\DeliveryDay as DeliveryDayDocument; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DeliveryDay; + +final class DeliveryDayPurgeTagProvider implements PurgeTagProviderInterface +{ + public function getTags(object $resource, Operation $operation, array $context = []): iterable + { + $previousResource = $context['previous_data'] ?? null; + + yield from $this->getSupplierCollectionTags($resource); + if (\is_object($previousResource)) { + yield from $this->getSupplierCollectionTags($previousResource); + } + + if ($operation instanceof DeleteOperationInterface && ($resource instanceof DeliveryDay || $resource instanceof DeliveryDayDocument) && null !== $resource->id) { + yield \sprintf('/delivery_days/%d/history', $resource->id); + } + + if (MappedDeliveryDay::class === $operation->getClass() && $previousResource instanceof MappedDeliveryDay && $resource instanceof DeliveryDay) { + yield \sprintf('/mapped_delivery_days/day/%s', $previousResource->day); + yield \sprintf('/mapped_delivery_days/day/%s', $resource->day); + } + } + + /** + * @return string[] + */ + private function getSupplierCollectionTags(object $resource): array + { + if (!($resource instanceof DeliveryDay || $resource instanceof DeliveryDayDocument) || null === $resource->supplier?->id) { + return []; + } + + return [\sprintf('/suppliers/%d/delivery_days', $resource->supplier->id)]; + } +} diff --git a/tests/Fixtures/app/config/config_common.yml b/tests/Fixtures/app/config/config_common.yml index b1d280c406f..848e9d30bc4 100644 --- a/tests/Fixtures/app/config/config_common.yml +++ b/tests/Fixtures/app/config/config_common.yml @@ -507,6 +507,10 @@ services: class: ApiPlatform\Tests\Fixtures\TestBundle\HttpCache\TagCollectorDefault public: true + ApiPlatform\Tests\Fixtures\TestBundle\HttpCache\DeliveryDayPurgeTagProvider: + tags: + - name: 'api_platform.http_cache.purge_tag_provider' + ApiPlatform\Tests\Fixtures\TestBundle\Parameter\CustomGroupParameterProvider: tags: - name: 'api_platform.parameter_provider' diff --git a/tests/Functional/HttpCache/PurgeTagProviderTest.php b/tests/Functional/HttpCache/PurgeTagProviderTest.php new file mode 100644 index 00000000000..e8bfb685cb3 --- /dev/null +++ b/tests/Functional/HttpCache/PurgeTagProviderTest.php @@ -0,0 +1,118 @@ + + * + * 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\HttpCache; + +use ApiPlatform\Test\ApiTestCase; +use ApiPlatform\Tests\Fixtures\NullPurger; +use ApiPlatform\Tests\Fixtures\TestBundle\ApiResource\MappedDeliveryDay; +use ApiPlatform\Tests\Fixtures\TestBundle\Document\Supplier as SupplierDocument; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\DeliveryDay; +use ApiPlatform\Tests\Fixtures\TestBundle\Entity\Supplier; +use ApiPlatform\Tests\RecreateSchemaTrait; +use ApiPlatform\Tests\SetupClassResourcesTrait; + +/** + * @see https://github.com/api-platform/core/issues/8123 + */ +final class PurgeTagProviderTest extends ApiTestCase +{ + use RecreateSchemaTrait; + use SetupClassResourcesTrait; + + protected static ?bool $alwaysBootKernel = false; + + /** + * @return class-string[] + */ + public static function getResources(): array + { + return [Supplier::class, DeliveryDay::class, MappedDeliveryDay::class]; + } + + public function testSubresourceCollectionIsPurged(): void + { + $this->recreateSchema([Supplier::class, DeliveryDay::class]); + + $manager = $this->getManager(); + foreach (['First', 'Second'] as $name) { + $supplier = $this->isMongoDB() ? new SupplierDocument() : new Supplier(); + $supplier->name = $name; + $manager->persist($supplier); + } + $manager->flush(); + + $client = self::createClient(); + + $client->request('GET', '/suppliers/1/delivery_days'); + $this->assertResponseStatusCodeSame(200); + $this->assertResponseHeaderSame('Cache-Tags', '/suppliers/1/delivery_days'); + + $this->purger()->clear(); + $client->request('POST', '/delivery_days', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['supplier' => '/suppliers/1', 'day' => 'monday'], + ]); + $this->assertResponseStatusCodeSame(201); + $this->assertContains('/suppliers/1/delivery_days', $this->purger()->getIris()); + + // Moving to another supplier purges both the previous and the new parent collection. + $this->purger()->clear(); + $client->request('PUT', '/delivery_days/1', [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['supplier' => '/suppliers/2', 'day' => 'monday'], + ]); + $this->assertResponseStatusCodeSame(200); + $this->assertContains('/suppliers/1/delivery_days', $this->purger()->getIris()); + $this->assertContains('/suppliers/2/delivery_days', $this->purger()->getIris()); + + $this->purger()->clear(); + $client->request('DELETE', '/delivery_days/1'); + $this->assertResponseStatusCodeSame(204); + $this->assertContains('/suppliers/2/delivery_days', $this->purger()->getIris()); + $this->assertContains('/delivery_days/1/history', $this->purger()->getIris()); + } + + public function testMappedResourceUpdateReceivesEntityAndPreviousResource(): void + { + if ($this->isMongoDB()) { + $this->markTestSkipped('The ObjectMapper stateOptions entity is ORM only.'); + } + + $this->recreateSchema([Supplier::class, DeliveryDay::class]); + + $deliveryDay = new DeliveryDay(); + $deliveryDay->day = 'monday'; + $manager = $this->getManager(); + $manager->persist($deliveryDay); + $manager->flush(); + + $this->purger()->clear(); + self::createClient()->request('PUT', '/mapped_delivery_days/'.$deliveryDay->id, [ + 'headers' => ['Content-Type' => 'application/ld+json'], + 'json' => ['day' => 'tuesday'], + ]); + + $this->assertResponseStatusCodeSame(200); + $this->assertContains('/mapped_delivery_days/day/monday', $this->purger()->getIris()); + $this->assertContains('/mapped_delivery_days/day/tuesday', $this->purger()->getIris()); + } + + private function purger(): NullPurger + { + $purger = static::getContainer()->get('test.api_platform.http_cache.purger'); + \assert($purger instanceof NullPurger); + + return $purger; + } +}