Total Complexity | 59 |
Total Lines | 344 |
Duplicated Lines | 0 % |
Changes | 13 | ||
Bugs | 2 | Features | 1 |
Complex classes like Cache often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Cache, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
27 | class Cache implements CacheInterface |
||
28 | { |
||
29 | /** @var Builder */ |
||
30 | protected $builder; |
||
31 | |||
32 | /** @var string */ |
||
33 | protected $cacheDir; |
||
34 | |||
35 | public function __construct(Builder $builder, string $pool = '') |
||
36 | { |
||
37 | $this->builder = $builder; |
||
38 | $this->cacheDir = Util::joinFile($builder->getConfig()->getCachePath(), $pool); |
||
39 | } |
||
40 | |||
41 | /** |
||
42 | * {@inheritdoc} |
||
43 | */ |
||
44 | public function set($key, $value, $ttl = null): bool |
||
45 | { |
||
46 | try { |
||
47 | $key = self::sanitizeKey($key); |
||
48 | $this->prune($key); |
||
49 | // put file content in a dedicated file |
||
50 | if (\is_array($value) && !empty($value['content']) && !empty($value['path'])) { |
||
51 | Util\File::getFS()->dumpFile($this->getContentFilePathname($value['path']), $value['content']); |
||
52 | unset($value['content']); |
||
53 | } |
||
54 | // serialize data |
||
55 | $data = serialize([ |
||
56 | 'value' => $value, |
||
57 | 'expiration' => $ttl === null ? null : time() + $this->duration($ttl), |
||
58 | ]); |
||
59 | Util\File::getFS()->dumpFile($this->getFilePathname($key), $data); |
||
60 | } catch (\Exception $e) { |
||
61 | $this->builder->getLogger()->error($e->getMessage()); |
||
62 | |||
63 | return false; |
||
64 | } |
||
65 | |||
66 | return true; |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * {@inheritdoc} |
||
71 | */ |
||
72 | public function has($key): bool |
||
73 | { |
||
74 | $key = self::sanitizeKey($key); |
||
75 | if (!Util\File::getFS()->exists($this->getFilePathname($key))) { |
||
76 | return false; |
||
77 | } |
||
78 | |||
79 | return true; |
||
80 | } |
||
81 | |||
82 | /** |
||
83 | * {@inheritdoc} |
||
84 | */ |
||
85 | public function get($key, $default = null): mixed |
||
86 | { |
||
87 | try { |
||
88 | $key = self::sanitizeKey($key); |
||
89 | // return default value if file doesn't exists |
||
90 | if (false === $content = Util\File::fileGetContents($this->getFilePathname($key))) { |
||
91 | return $default; |
||
92 | } |
||
93 | // unserialize data |
||
94 | $data = unserialize($content); |
||
95 | // check expiration |
||
96 | if ($data['expiration'] !== null && $data['expiration'] <= time()) { |
||
97 | $this->builder->getLogger()->debug(\sprintf('Cache expired: "%s"', $key)); |
||
98 | // remove expired cache |
||
99 | if ($this->delete($key)) { |
||
100 | // remove content file if exists |
||
101 | if (!empty($data['value']['path'])) { |
||
102 | $this->deleteContentFile($data['value']['path']); |
||
103 | } |
||
104 | } |
||
105 | |||
106 | return $default; |
||
107 | } |
||
108 | // get content from dedicated file |
||
109 | if (\is_array($data['value']) && isset($data['value']['path'])) { |
||
110 | if (false !== $content = Util\File::fileGetContents($this->getContentFilePathname($data['value']['path']))) { |
||
111 | $data['value']['content'] = $content; |
||
112 | } |
||
113 | } |
||
114 | } catch (\Exception $e) { |
||
115 | $this->builder->getLogger()->error($e->getMessage()); |
||
116 | |||
117 | return $default; |
||
118 | } |
||
119 | |||
120 | return $data['value']; |
||
121 | } |
||
122 | |||
123 | /** |
||
124 | * {@inheritdoc} |
||
125 | */ |
||
126 | public function delete($key): bool |
||
127 | { |
||
128 | try { |
||
129 | $key = self::sanitizeKey($key); |
||
130 | Util\File::getFS()->remove($this->getFilePathname($key)); |
||
131 | $this->prune($key); |
||
132 | } catch (\Exception $e) { |
||
133 | $this->builder->getLogger()->error($e->getMessage()); |
||
134 | |||
135 | return false; |
||
136 | } |
||
137 | |||
138 | return true; |
||
139 | } |
||
140 | |||
141 | /** |
||
142 | * {@inheritdoc} |
||
143 | */ |
||
144 | public function clear(): bool |
||
145 | { |
||
146 | try { |
||
147 | Util\File::getFS()->remove($this->cacheDir); |
||
148 | } catch (\Exception $e) { |
||
149 | $this->builder->getLogger()->error($e->getMessage()); |
||
150 | |||
151 | return false; |
||
152 | } |
||
153 | |||
154 | return true; |
||
155 | } |
||
156 | |||
157 | /** |
||
158 | * {@inheritdoc} |
||
159 | */ |
||
160 | public function getMultiple($keys, $default = null): iterable |
||
161 | { |
||
162 | throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__)); |
||
163 | } |
||
164 | |||
165 | /** |
||
166 | * {@inheritdoc} |
||
167 | */ |
||
168 | public function setMultiple($values, $ttl = null): bool |
||
169 | { |
||
170 | throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__)); |
||
171 | } |
||
172 | |||
173 | /** |
||
174 | * {@inheritdoc} |
||
175 | */ |
||
176 | public function deleteMultiple($keys): bool |
||
177 | { |
||
178 | throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__)); |
||
179 | } |
||
180 | |||
181 | /** |
||
182 | * Creates key from a name and a hash: "$name__HASH__VERSION". |
||
183 | */ |
||
184 | public function createKey(string $name, string $hash): string |
||
185 | { |
||
186 | $name = self::sanitizeKey($name); |
||
187 | |||
188 | return \sprintf('%s__%s__%s', $name, $hash, $this->builder->getVersion()); |
||
189 | } |
||
190 | |||
191 | /** |
||
192 | * Creates key from a string: "$name__HASH__VERSION". |
||
193 | * $name is optional to add a human readable name to the key. |
||
194 | */ |
||
195 | public function createKeyFromValue(?string $name, string $value): string |
||
196 | { |
||
197 | $hash = hash('md5', $value); |
||
198 | $name = $name ?? $hash; |
||
199 | |||
200 | return $this->createKey($name, $hash); |
||
201 | } |
||
202 | |||
203 | /** |
||
204 | * Creates key from an Asset: "$path_$ext_$tags__HASH__VERSION". |
||
205 | */ |
||
206 | public function createKeyFromAsset(Asset $asset, ?array $tags = null): string |
||
207 | { |
||
208 | $t = $tags; |
||
209 | $tags = []; |
||
210 | |||
211 | if ($t !== null) { |
||
212 | foreach ($t as $key => $value) { |
||
213 | switch (\gettype($value)) { |
||
214 | case 'boolean': |
||
215 | if ($value === true) { |
||
216 | $tags[] = $key; |
||
217 | } |
||
218 | break; |
||
219 | case 'string': |
||
220 | case 'integer': |
||
221 | if (!empty($value)) { |
||
222 | $tags[] = substr($key, 0, 1) . $value; |
||
223 | } |
||
224 | break; |
||
225 | } |
||
226 | } |
||
227 | } |
||
228 | |||
229 | $tagsInline = implode('_', str_replace('_', '', $tags)); |
||
230 | $name = "{$asset['_path']}_{$asset['ext']}_$tagsInline"; |
||
231 | |||
232 | // backward compatibility |
||
233 | if (empty($asset['hash'])) { |
||
234 | throw new RuntimeException(\sprintf('Asset "%s" has no hash. Please clear cache and retry.', $name)); |
||
235 | } |
||
236 | |||
237 | return $this->createKey($name, $asset['hash']); |
||
|
|||
238 | } |
||
239 | |||
240 | /** |
||
241 | * Creates key from a file: "RelativePathname__MD5". |
||
242 | * |
||
243 | * @throws RuntimeException |
||
244 | */ |
||
245 | public function createKeyFromFile(\Symfony\Component\Finder\SplFileInfo $file): string |
||
246 | { |
||
247 | if (false === $content = Util\File::fileGetContents($file->getRealPath())) { |
||
248 | throw new RuntimeException(\sprintf('Can\'t create cache key for "%s".', $file)); |
||
249 | } |
||
250 | |||
251 | return $this->createKeyFromValue($file->getRelativePathname(), $content); |
||
252 | } |
||
253 | |||
254 | /** |
||
255 | * Clear cache by pattern. |
||
256 | */ |
||
257 | public function clearByPattern(string $pattern): int |
||
284 | } |
||
285 | |||
286 | /** |
||
287 | * Returns cache content file pathname from path. |
||
288 | */ |
||
289 | public function getContentFilePathname(string $path): string |
||
290 | { |
||
291 | $path = str_replace(['https://', 'http://'], '', $path); // remove protocol (if URL) |
||
292 | |||
293 | return Util::joinFile($this->cacheDir, 'files', $path); |
||
294 | } |
||
295 | |||
296 | /** |
||
297 | * Returns cache file pathname from key. |
||
298 | */ |
||
299 | private function getFilePathname(string $key): string |
||
300 | { |
||
301 | return Util::joinFile($this->cacheDir, "$key.ser"); |
||
302 | } |
||
303 | |||
304 | /** |
||
305 | * Prepares and validate $key. |
||
306 | */ |
||
307 | public static function sanitizeKey(string $key): string |
||
316 | } |
||
317 | |||
318 | /** |
||
319 | * Removes previous cache files. |
||
320 | */ |
||
321 | private function prune(string $key): bool |
||
340 | } |
||
341 | |||
342 | /** |
||
343 | * Convert the various expressions of a TTL value into duration in seconds. |
||
344 | */ |
||
345 | protected function duration(int|\DateInterval $ttl): int |
||
355 | } |
||
356 | |||
357 | /** |
||
358 | * Removes the cache content file. |
||
359 | */ |
||
360 | protected function deleteContentFile(string $path): bool |
||
371 | } |
||
372 | } |
||
373 |