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 WincacheAdapter 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 | $result = wincache_ucache_get($this->addNamespaceToKey($key), $success); |
||
31 | |||
32 | if (!$success) { |
||
33 | throw new KeyNotFoundException(); |
||
34 | } |
||
35 | |||
36 | return $result; |
||
37 | } |
||
38 | |||
39 | public function getMulti(array $keys): array |
||
40 | { |
||
41 | $namespacedKeys = $this->addNamespaceToKeys($keys); |
||
42 | $namespacedValues = wincache_ucache_get($namespacedKeys, $success); |
||
43 | |||
44 | if (!$success) { |
||
45 | return []; |
||
46 | } |
||
47 | |||
48 | return $this->removeNamespaceFromKeys($namespacedValues); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * @param mixed $value |
||
53 | */ |
||
54 | public function set(string $key, $value): bool |
||
55 | { |
||
56 | return wincache_ucache_set($this->addNamespaceToKey($key), $value, $this->ttl); |
||
57 | } |
||
58 | |||
59 | public function setMulti(array $data): bool |
||
60 | { |
||
61 | $namespacedData = $this->addNamespaceToKeys($data, true); |
||
62 | $errors = wincache_ucache_add($namespacedData, null, $this->ttl); |
||
63 | |||
64 | return empty($errors); |
||
65 | } |
||
66 | |||
67 | public function contains(string $key): bool |
||
68 | { |
||
69 | return wincache_ucache_exists($this->addNamespaceToKey($key)); |
||
70 | } |
||
71 | |||
72 | public function delete(string $key): bool |
||
73 | { |
||
74 | wincache_ucache_delete($this->addNamespaceToKey($key)); |
||
75 | |||
76 | return true; |
||
77 | } |
||
78 | |||
79 | public function deleteMulti(array $keys): bool |
||
80 | { |
||
81 | foreach ($keys as $key) { |
||
82 | wincache_ucache_delete($this->addNamespaceToKey($key)); |
||
83 | } |
||
84 | |||
85 | return true; |
||
86 | } |
||
87 | |||
88 | public function flush(): bool |
||
89 | { |
||
90 | return wincache_ucache_clear(); |
||
91 | } |
||
92 | } |
||
93 |