-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSimpleCacheContainer.php
115 lines (97 loc) · 2.49 KB
/
SimpleCacheContainer.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
declare(strict_types=1);
namespace Dhii\Container;
use Dhii\Collection\ClearableContainerInterface;
use Dhii\Collection\MutableContainerInterface;
use Dhii\Container\Exception\ContainerException;
use Dhii\Container\Exception\NotFoundException;
use Exception;
use Psr\SimpleCache\CacheInterface;
class SimpleCacheContainer implements
MutableContainerInterface,
ClearableContainerInterface
{
/**
* @var CacheInterface
*/
protected $storage;
/**
* @var int
*/
protected $ttl;
public function __construct(CacheInterface $storage, int $ttl)
{
$this->storage = $storage;
$this->ttl = $ttl;
}
/**
* @inheritDoc
*/
public function get(string $id)
{
$storage = $this->storage;
try {
if (!$storage->has($id)) {
return new NotFoundException(sprintf('Key "%1$s" not found', $id));
}
$value = $storage->get($id);
} catch (Exception $e) {
throw new ContainerException(sprintf('Could not retrieve value for key "%1$s"', $id), 0, $e);
}
return $value;
}
/**
* @inheritDoc
*/
public function has(string $id): bool
{
$storage = $this->storage;
try {
$has = $storage->has($id);
} catch (Exception $e) {
throw new ContainerException(sprintf('Could not check for key "%1$s"', $id), 0, $e);
}
return $has;
}
/**
* @inheritDoc
*/
public function set(string $key, $value): void
{
$storage = $this->storage;
$ttl = $this->ttl;
try {
$storage->set($key, $value, $ttl);
} catch (Exception $e) {
throw new ContainerException(
sprintf('Could not set key "%1$s" with value "%2$s"', $key, (string) $value),
0,
$e
);
}
}
/**
* @inheritDoc
*/
public function unset(string $key): void
{
$storage = $this->storage;
try {
$storage->delete($key);
} catch (Exception $e) {
throw new ContainerException(sprintf('Could not unset key "%1$s"', $key), 0, $e);
}
}
/**
* @inheritDoc
*/
public function clear(): void
{
$storage = $this->storage;
try {
$storage->clear();
} catch (Exception $e) {
throw new ContainerException('Could not clear container', 0, $e);
}
}
}