-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetteCacheStorage.php
More file actions
93 lines (79 loc) · 2.59 KB
/
NetteCacheStorage.php
File metadata and controls
93 lines (79 loc) · 2.59 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
<?php
declare(strict_types=1);
namespace SixtyEightPublishers\AmpClient\Bridge\Nette;
use Nette\Caching\Cache;
use Nette\Caching\Storage;
use Psr\Log\LoggerInterface;
use SixtyEightPublishers\AmpClient\Http\Cache\CachedResponse;
use SixtyEightPublishers\AmpClient\Http\Cache\CacheKey;
use SixtyEightPublishers\AmpClient\Http\Cache\CacheStorageInterface;
use SixtyEightPublishers\AmpClient\Http\Cache\Expiration;
use Throwable;
final class NetteCacheStorage implements CacheStorageInterface
{
private Cache $cache;
private ?LoggerInterface $logger;
public function __construct(Storage $storage, ?LoggerInterface $logger = null)
{
$this->cache = new Cache($storage, self::class);
$this->logger = $logger;
}
public function get(CacheKey $key): ?CachedResponse
{
try {
$response = $this->cache->load($key->getValue());
if (!$response instanceof CachedResponse) {
$this->delete($key);
return null;
}
return $response;
} catch (Throwable $e) {
if (null !== $this->logger) {
$this->logger->error('[AMP] Unable to load response from cache: ' . $e->getMessage(), [
'exception' => $e,
]);
}
return null;
}
}
public function save(CachedResponse $response, Expiration $expiration): void
{
try {
$this->cache->save($response->getKey()->getValue(), $response, [
Cache::EXPIRE => $expiration->getValue(),
]);
} catch (Throwable $e) {
if (null !== $this->logger) {
$this->logger->error('[AMP] Unable to save response to cache: ' . $e->getMessage(), [
'exception' => $e,
]);
}
}
}
public function delete(CacheKey $key): void
{
try {
$this->cache->remove($key->getValue());
} catch (Throwable $e) {
if (null !== $this->logger) {
$this->logger->error('[AMP] Unable to delete response from cache: ' . $e->getMessage(), [
'exception' => $e,
]);
}
}
}
public function clear(): void
{
try {
$this->cache->clean([
Cache::ALL,
]);
} catch (Throwable $e) {
if (null !== $this->logger) {
$this->logger->error('[AMP] Unable to clear cache: ' . $e->getMessage(), [
'exception' => $e,
]);
}
}
}
}