-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SurrogateKeysPurger.php
89 lines (76 loc) · 2.49 KB
/
SurrogateKeysPurger.php
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
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Surrogate keys purger.
*
* @author Sylvain Combraque <[email protected]>
*/
class SurrogateKeysPurger implements PurgerInterface
{
private const MAX_HEADER_SIZE_PER_BATCH = 1500;
private const SEPARATOR = ', ';
private const HEADER = 'Surrogate-Key';
/**
* @param HttpClientInterface[] $clients
*/
public function __construct(protected readonly iterable $clients, protected readonly int $maxHeaderLength = self::MAX_HEADER_SIZE_PER_BATCH, protected readonly string $header = self::HEADER, protected readonly string $separator = self::SEPARATOR)
{
}
/**
* @return \Iterator<string>
*/
private function getChunkedIris(array $iris): \Iterator
{
if (!$iris) {
return;
}
$chunk = array_shift($iris);
foreach ($iris as $iri) {
$nextChunk = \sprintf('%s%s%s', $chunk, $this->separator, $iri);
if (\strlen($nextChunk) <= $this->maxHeaderLength) {
$chunk = $nextChunk;
continue;
}
yield $chunk;
$chunk = $iri;
}
yield $chunk;
}
/**
* {@inheritdoc}
*/
public function purge(array $iris): void
{
foreach ($this->getChunkedIris($iris) as $chunk) {
if (\strlen((string) $chunk) > $this->maxHeaderLength) {
throw new RuntimeException(\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.', $chunk, $this->maxHeaderLength));
}
foreach ($this->clients as $client) {
$client->request(
Request::METHOD_PURGE,
'',
['headers' => [$this->header => $chunk]]
);
}
}
}
/**
* {@inheritdoc}
*/
public function getResponseHeaders(array $iris): array
{
return [$this->header => implode($this->separator, $iris)];
}
}