1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Components Bundle Project |
5
|
|
|
* |
6
|
|
|
* (c) Daniel West <[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 Silverback\ApiComponentsBundle\EventListener\Doctrine; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Api\IriConverterInterface; |
17
|
|
|
use ApiPlatform\Core\Exception\InvalidArgumentException; |
18
|
|
|
use ApiPlatform\Core\Exception\RuntimeException; |
19
|
|
|
use ApiPlatform\Core\HttpCache\PurgerInterface; |
20
|
|
|
use Doctrine\ORM\PersistentCollection; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Purges desired resources on when doctrine is flushed from the proxy cache. |
24
|
|
|
* |
25
|
|
|
* @author Daniel West <[email protected]> |
26
|
|
|
* |
27
|
|
|
* @experimental |
28
|
|
|
*/ |
29
|
|
|
class PurgeHttpCacheListener |
30
|
|
|
{ |
31
|
|
|
private PurgerInterface $purger; |
32
|
|
|
private IriConverterInterface $iriConverter; |
33
|
|
|
private array $tags = []; |
34
|
|
|
|
35
|
|
|
public function __construct(PurgerInterface $purger, IriConverterInterface $iriConverter) |
36
|
|
|
{ |
37
|
|
|
$this->purger = $purger; |
38
|
|
|
$this->iriConverter = $iriConverter; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Purges tags collected during this request, and clears the tag list. |
43
|
|
|
* |
44
|
|
|
* @see \ApiPlatform\Core\Bridge\Doctrine\EventListener\PurgeHttpCacheListener |
45
|
|
|
*/ |
46
|
|
|
public function postFlush(): void |
47
|
|
|
{ |
48
|
|
|
if (empty($this->tags)) { |
49
|
|
|
return; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$this->purger->purge(array_values($this->tags)); |
53
|
|
|
$this->tags = []; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @see \ApiPlatform\Core\Bridge\Doctrine\EventListener\PurgeHttpCacheListener |
58
|
|
|
*/ |
59
|
|
|
public function addTagsFor($value): void |
60
|
|
|
{ |
61
|
|
|
if (!$value) { |
62
|
|
|
return; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
if (!is_iterable($value)) { |
66
|
|
|
$this->addTagForItem($value); |
67
|
|
|
|
68
|
|
|
return; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
if ($value instanceof PersistentCollection) { |
72
|
|
|
$value = clone $value; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
foreach ($value as $v) { |
76
|
|
|
$this->addTagForItem($v); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @see \ApiPlatform\Core\Bridge\Doctrine\EventListener\PurgeHttpCacheListener |
82
|
|
|
*/ |
83
|
|
|
private function addTagForItem($value): void |
84
|
|
|
{ |
85
|
|
|
try { |
86
|
|
|
$iri = $this->iriConverter->getIriFromItem($value); |
87
|
|
|
$this->tags[$iri] = $iri; |
88
|
|
|
} catch (InvalidArgumentException $e) { |
|
|
|
|
89
|
|
|
} catch (RuntimeException $e) { |
|
|
|
|
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|