Total Complexity | 9 |
Total Lines | 81 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
12 | abstract class Manager extends Component implements ManagerInterface |
||
13 | { |
||
14 | /** |
||
15 | * @var CacheInterface $cache |
||
16 | */ |
||
17 | public $cache = 'cache'; |
||
18 | |||
19 | /** |
||
20 | * @var bool $enableCache whether enable caching. |
||
21 | */ |
||
22 | public $enableCache = true; |
||
23 | |||
24 | /** |
||
25 | * @var Mutex $mutex |
||
26 | */ |
||
27 | public $mutex = 'mutex'; |
||
28 | |||
29 | /** |
||
30 | * @var string $cacheKey |
||
31 | */ |
||
32 | public $cacheKey = self::class; |
||
33 | |||
34 | /** |
||
35 | * @var int $duration |
||
36 | */ |
||
37 | public $duration = 600; |
||
38 | |||
39 | 8 | public function init() |
|
40 | { |
||
41 | 8 | parent::init(); |
|
42 | |||
43 | 8 | $this->cache = Instance::ensure($this->cache, CacheInterface::class); |
|
44 | 8 | $this->mutex = Instance::ensure($this->mutex, Mutex::class); |
|
45 | 8 | } |
|
46 | |||
47 | private $data; |
||
48 | |||
49 | 6 | public function get(string $id, ?string $defaultValue = null): ?string |
|
53 | } |
||
54 | |||
55 | 7 | public function getAll(): array |
|
56 | { |
||
57 | 7 | if ($this->data !== null) { |
|
58 | 4 | return $this->data; |
|
59 | } |
||
60 | |||
61 | // retrieves from cache |
||
62 | 7 | if ($this->enableCache && ($this->data = $this->cache->get($this->cacheKey)) !== false) { |
|
63 | 3 | return $this->data; |
|
64 | } |
||
65 | |||
66 | // retrieves all data |
||
67 | 7 | $this->data = $this->load(); |
|
68 | |||
69 | // cache |
||
70 | 7 | if ($this->enableCache) { |
|
71 | 5 | $lock = $this->cacheKey; |
|
72 | // acquire lock avoid concurrence |
||
73 | 5 | if ($this->mutex->acquire($lock, 0)) { |
|
74 | 5 | $this->cache->set($this->cacheKey, $this->data, $this->duration); |
|
75 | } |
||
76 | } |
||
77 | |||
78 | 7 | return $this->data; |
|
79 | } |
||
80 | |||
81 | /** |
||
82 | * Loads all data as array that mapping from id to value. |
||
83 | * |
||
84 | * @return array |
||
85 | */ |
||
86 | abstract protected function load(): array; |
||
87 | |||
88 | 1 | public function flushCache(): bool |
|
93 | } |
||
94 | } |
||
95 |