forked from api-platform/core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVarnishXKeyPurger.php
More file actions
105 lines (83 loc) · 2.85 KB
/
VarnishXKeyPurger.php
File metadata and controls
105 lines (83 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?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 Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Purges Varnish XKey.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class VarnishXKeyPurger implements PurgerInterface
{
private const VARNISH_MAX_HEADER_LENGTH = 8000;
/**
* @param HttpClientInterface[] $clients
*/
public function __construct(private readonly array $clients, private readonly int $maxHeaderLength = self::VARNISH_MAX_HEADER_LENGTH, private readonly string $xkeyGlue = ' ')
{
}
/**
* {@inheritdoc}
*/
public function purge(array $iris): void
{
if (!$iris) {
return;
}
$irisChunks = array_chunk($iris, \count($iris));
foreach ($irisChunks as $irisChunk) {
$this->purgeIris($irisChunk);
}
}
/**
* {@inheritdoc}
*/
public function getResponseHeaders(array $iris): array
{
return ['xkey' => implode($this->xkeyGlue, $iris)];
}
private function purgeIris(array $iris): void
{
foreach ($this->chunkKeys($iris) as $keys) {
$this->purgeKeys($keys);
}
}
private function purgeKeys(string $keys): void
{
foreach ($this->clients as $client) {
$client->request('PURGE', '', ['headers' => ['xkey' => $keys]]);
}
}
private function chunkKeys(array $keys): iterable
{
$concatenatedKeys = implode($this->xkeyGlue, $keys);
// If all keys fit in the header, we can return them
if (\strlen($concatenatedKeys) <= $this->maxHeaderLength) {
yield $concatenatedKeys;
return;
}
$currentHeader = '';
foreach ($keys as $position => $key) {
if (\strlen((string) $key) > $this->maxHeaderLength) {
throw new \Exception(sprintf('IRI "%s" is too long to fit current max header length (currently set to "%s"). You can increase it using the "api_platform.http_cache.invalidation.max_header_length" parameter.', $key, $this->maxHeaderLength));
}
$headerCandidate = sprintf('%s%s%s', $currentHeader, $position > 0 ? $this->xkeyGlue : '', $key);
if (\strlen($headerCandidate) > $this->maxHeaderLength) {
$nextKeys = \array_slice($keys, $position, \count($keys) - $position);
yield $currentHeader;
yield from $this->chunkKeys($nextKeys);
break;
}
// Key can be added to header
$currentHeader .= sprintf('%s%s', $position > 0 ? $this->xkeyGlue : '', $key);
}
}
}