1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the API Platform project. |
5
|
|
|
* |
6
|
|
|
* (c) Kévin Dunglas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace ApiPlatform\Core\HttpCache\EventListener; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Api\IriConverterInterface; |
17
|
|
|
use ApiPlatform\Core\Util\RequestAttributesExtractor; |
18
|
|
|
use Symfony\Component\HttpKernel\Event\FilterResponseEvent; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Sets the list of resources' IRIs included in this response in the "Cache-Tags" HTTP header. |
22
|
|
|
* |
23
|
|
|
* The "Cache-Tags" is used because it is supported by CloudFlare. |
24
|
|
|
* |
25
|
|
|
* @see https://support.cloudflare.com/hc/en-us/articles/206596608-How-to-Purge-Cache-Using-Cache-Tags-Enterprise-only- |
26
|
|
|
* |
27
|
|
|
* @author Kévin Dunglas <[email protected]> |
28
|
|
|
* |
29
|
|
|
* @experimental |
30
|
|
|
*/ |
31
|
|
|
final class AddTagsListener |
32
|
|
|
{ |
33
|
|
|
private $iriConverter; |
34
|
|
|
|
35
|
|
|
public function __construct(IriConverterInterface $iriConverter) |
36
|
|
|
{ |
37
|
|
|
$this->iriConverter = $iriConverter; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Adds the "Cache-Tags" header. |
42
|
|
|
* |
43
|
|
|
* @param FilterResponseEvent $event |
44
|
|
|
*/ |
45
|
|
|
public function onKernelResponse(FilterResponseEvent $event) |
46
|
|
|
{ |
47
|
|
|
$request = $event->getRequest(); |
48
|
|
|
$response = $event->getResponse(); |
49
|
|
|
|
50
|
|
|
if ( |
51
|
|
|
!$request->isMethodCacheable() |
52
|
|
|
|| !$response->isCacheable() |
53
|
|
|
|| (!$attributes = RequestAttributesExtractor::extractAttributes($request)) |
54
|
|
|
|| !$resources = $request->attributes->get('_resources') |
55
|
|
|
) { |
56
|
|
|
return; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
if (isset($attributes['collection_operation_name'])) { |
60
|
|
|
// Allows to purge collections |
61
|
|
|
$iri = $this->iriConverter->getIriFromResourceClass($attributes['resource_class']); |
62
|
|
|
$resources[$iri] = $iri; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if (!$resources) { |
66
|
|
|
return; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$event->getResponse()->headers->set('Cache-Tags', implode(',', $resources)); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|