Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
9 | class ApcuAdapter extends AbstractAdapter implements AdapterInterface |
||
10 | { |
||
11 | protected int $ttl = 0; |
||
|
|||
12 | |||
13 | public function __construct(array $config = []) |
||
14 | { |
||
15 | // config |
||
16 | if (isset($config['ttl'])) { |
||
17 | $this->ttl = (int) $config['ttl']; |
||
18 | } |
||
19 | |||
20 | if (isset($config['cache_not_found_keys'])) { |
||
21 | $this->cacheNotFoundKeys = (bool) $config['cache_not_found_keys']; |
||
22 | } |
||
23 | } |
||
24 | |||
25 | /** |
||
26 | * @return mixed |
||
27 | */ |
||
28 | public function get(string $key) |
||
29 | { |
||
30 | $value = apcu_fetch($this->addNamespaceToKey($key), $success); |
||
31 | |||
32 | if (!$success) { |
||
33 | throw new KeyNotFoundException(); |
||
34 | } |
||
35 | |||
36 | return $value; |
||
37 | } |
||
38 | |||
39 | public function getMulti(array $keys): array |
||
40 | { |
||
41 | $namespacedKeys = apcu_fetch($this->addNamespaceToKeys($keys)); |
||
42 | |||
43 | return $this->removeNamespaceFromKeys($namespacedKeys); |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * @param mixed $value |
||
48 | */ |
||
49 | public function set(string $key, $value): bool |
||
50 | { |
||
51 | return apcu_store($this->addNamespaceToKey($key), $value, $this->ttl); |
||
52 | } |
||
53 | |||
54 | public function setMulti(array $data): bool |
||
55 | { |
||
56 | $namespacedData = $this->addNamespaceToKeys($data, true); |
||
57 | $errors = apcu_store($namespacedData, $this->ttl); |
||
58 | |||
59 | return empty($errors); |
||
60 | } |
||
61 | |||
62 | public function contains(string $key): bool |
||
63 | { |
||
64 | return apcu_exists($this->addNamespaceToKey($key)); |
||
65 | } |
||
66 | |||
67 | public function delete(string $key): bool |
||
68 | { |
||
69 | apcu_delete($this->addNamespaceToKey($key)); |
||
70 | |||
71 | return true; |
||
72 | } |
||
73 | |||
74 | public function deleteMulti(array $keys): bool |
||
75 | { |
||
76 | foreach ($keys as $key) { |
||
77 | apcu_delete($this->addNamespaceToKey($key)); |
||
78 | } |
||
79 | |||
80 | return true; |
||
81 | } |
||
82 | |||
83 | public function flush(): bool |
||
84 | { |
||
85 | return apcu_clear_cache(); |
||
86 | } |
||
87 | } |
||
88 |