-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCliHttpCache.php
More file actions
88 lines (73 loc) · 2.1 KB
/
CliHttpCache.php
File metadata and controls
88 lines (73 loc) · 2.1 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
<?php
declare(strict_types=1);
namespace BEAR\QueryRepository;
use BEAR\Sunday\Extension\Transfer\HttpCacheInterface;
use Override;
use function assert;
use function is_string;
use function parse_str;
use function sprintf;
use function str_replace;
use function strtoupper;
use const PHP_EOL;
final readonly class CliHttpCache implements HttpCacheInterface
{
public function __construct(
private ResourceStorageInterface $storage,
) {
}
/**
* {@inheritDoc}
*/
#[Override]
public function isNotModified(array $server): bool
{
$etag = $this->getEtag($server);
if ($etag === null) {
return false;
}
return $this->storage->hasEtag($etag);
}
/**
* {@inheritDoc}
*
* @return void
*/
#[Override]
public function transfer()
{
echo '304 Not Modified' . PHP_EOL . PHP_EOL;
}
/** @return array<string, string> */
private function getServer(string $query): array
{
parse_str($query, $headers);
$server = [];
foreach ($headers as $key => $header) {
assert(is_string($header));
assert(is_string($key));
$server[$this->getServerKey($key)] = $header;
}
return $server;
}
private function getServerKey(string $key): string
{
return sprintf('HTTP_%s', strtoupper(str_replace('-', '_', $key)));
}
/** @param array<string, mixed> $server */
private function getEtag(array $server): string|null
{
/** @psalm-suppress MixedAssignment */
$arg3 = $server['argv'][3] ?? ''; /* @phpstan-ignore-line */
assert(is_string($arg3));
$hasRequestHeaderInCli = isset($server['argc']) && $server['argc'] === 4 && $arg3;
if ($hasRequestHeaderInCli) {
/** @psalm-suppress MixedArrayAccess */
$server = $this->getServer($arg3);
}
if (isset($server[Header::HTTP_IF_NONE_MATCH]) && is_string($server[Header::HTTP_IF_NONE_MATCH])) {
return $server[Header::HTTP_IF_NONE_MATCH];
}
return null;
}
}