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 ApcAdapter 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 = apc_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 | $values = []; |
||
42 | |||
43 | foreach ($keys as $key) { |
||
44 | $value = apc_fetch($this->addNamespaceToKey($key), $success); |
||
45 | if ($success) { |
||
46 | $values[$key] = $value; |
||
47 | } |
||
48 | } |
||
49 | |||
50 | return $values; |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @param mixed $value |
||
55 | */ |
||
56 | public function set(string $key, $value): bool |
||
57 | { |
||
58 | return apc_store($this->addNamespaceToKey($key), $value, $this->ttl); |
||
59 | } |
||
60 | |||
61 | public function setMulti(array $data): bool |
||
62 | { |
||
63 | $namespacedData = $this->addNamespaceToKeys($data, true); |
||
64 | $errors = apc_store($namespacedData, $this->ttl); |
||
65 | |||
66 | return empty($errors); |
||
67 | } |
||
68 | |||
69 | public function contains(string $key): bool |
||
70 | { |
||
71 | return apc_exists($this->addNamespaceToKey($key)); |
||
72 | } |
||
73 | |||
74 | public function delete(string $key): bool |
||
75 | { |
||
76 | apc_delete($this->addNamespaceToKey($key)); |
||
77 | |||
78 | return true; |
||
79 | } |
||
80 | |||
81 | public function deleteMulti(array $keys): bool |
||
82 | { |
||
83 | foreach ($keys as $key) { |
||
84 | apc_delete($this->addNamespaceToKey($key)); |
||
85 | } |
||
86 | |||
87 | return true; |
||
88 | } |
||
89 | |||
90 | public function flush(): bool |
||
91 | { |
||
92 | return apc_clear_cache('user'); |
||
93 | } |
||
94 | } |
||
95 |