Skip to content
Merged
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
30 changes: 30 additions & 0 deletions src/HttpCache/PurgeTagProviderInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?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\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<string, mixed> $context $context['previous_data'] holds the API resource as read before the request, null on creation
*
* @return iterable<string>
*/
public function getTags(object $resource, Operation $operation, array $context = []): iterable;
}
72 changes: 72 additions & 0 deletions src/HttpCache/State/PurgeTagsProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?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\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<PurgeTagProviderInterface> $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<string, mixed> $context
*
* @return array<string, string>
*/
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;
}
}
119 changes: 119 additions & 0 deletions src/HttpCache/Tests/State/PurgeTagsProcessorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?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\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(), [], []);
}
}
16 changes: 16 additions & 0 deletions src/Laravel/ApiPlatformDeferredProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));

Expand Down
30 changes: 30 additions & 0 deletions src/Laravel/Tests/MockPurgeTagProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?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\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'];
}
}
104 changes: 104 additions & 0 deletions src/Laravel/Tests/PurgeTagProviderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?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\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());
}
}
Loading
Loading