1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BEAR\QueryRepository; |
6
|
|
|
|
7
|
|
|
use BEAR\Resource\AbstractRequest; |
8
|
|
|
use BEAR\Resource\ResourceInterface; |
9
|
|
|
use BEAR\Resource\ResourceObject; |
10
|
|
|
|
11
|
|
|
use function array_key_exists; |
12
|
|
|
use function assert; |
13
|
|
|
use function is_iterable; |
14
|
|
|
use function preg_replace_callback; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Donut cache resource state |
18
|
|
|
*/ |
19
|
|
|
final class ResourceDonut |
20
|
|
|
{ |
21
|
|
|
public const FOMRAT = '[le:%s]'; |
22
|
|
|
|
23
|
|
|
private const URI_REGEX = '/\[le:(.+)]/'; |
24
|
|
|
|
25
|
|
|
/** @param array<string, string> $headers */ |
26
|
|
|
public function __construct( |
27
|
|
|
private readonly string $template, |
28
|
|
|
private readonly array $headers, |
29
|
|
|
/** @readonly */ |
30
|
|
|
public int|null $ttl, |
31
|
|
|
/** @readonly */ |
32
|
|
|
public bool $isCacheble, |
33
|
|
|
) { |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function refresh(ResourceInterface $resource, ResourceObject $ro): ResourceObject |
37
|
|
|
{ |
38
|
|
|
$etags = new SurrogateKeys($ro->uri); |
39
|
|
|
$refreshView = preg_replace_callback(self::URI_REGEX, static function (array $matches) use ($resource, $etags): string { |
40
|
|
|
$uri = $matches[1]; |
41
|
|
|
$ro = $resource->get($uri); |
42
|
|
|
$ro->toString(); |
43
|
|
|
if (array_key_exists(Header::SURROGATE_KEY, $ro->headers)) { |
44
|
|
|
$etags->addTag($ro); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return (string) $ro->view; |
48
|
|
|
}, $this->template); |
49
|
|
|
|
50
|
|
|
$ro->headers = $this->headers; |
51
|
|
|
$ro->view = $refreshView; |
52
|
|
|
$etags->setSurrogateHeader($ro); |
53
|
|
|
|
54
|
|
|
return $ro; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function render(ResourceObject $ro, DonutRendererInterface $storage): ResourceObject |
58
|
|
|
{ |
59
|
|
|
$view = $storage->render($this->template); |
60
|
|
|
$ro->view = $view; |
61
|
|
|
|
62
|
|
|
return $ro; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public static function create(ResourceObject $ro, DonutRendererInterface $storage, SurrogateKeys $etags, int|null $ttl, bool $isCacheble): self |
66
|
|
|
{ |
67
|
|
|
assert(is_iterable($ro->body)); |
68
|
|
|
/** @var mixed $maybeRequest */ |
69
|
|
|
foreach ($ro->body as &$maybeRequest) { |
70
|
|
|
if ($maybeRequest instanceof AbstractRequest) { |
71
|
|
|
$maybeRequest = new DonutRequest($maybeRequest, $storage, $etags); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
unset($maybeRequest); |
76
|
|
|
$donutTemplate = (string) $ro; |
77
|
|
|
|
78
|
|
|
return new self($donutTemplate, $ro->headers, $ttl, $isCacheble); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|