| Total Complexity | 47 |
| Total Lines | 293 |
| Duplicated Lines | 0 % |
| Changes | 16 | ||
| Bugs | 1 | 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 |
||
| 22 | class Cache implements CacheInterface |
||
| 23 | { |
||
| 24 | /** @var Builder */ |
||
| 25 | protected $builder; |
||
| 26 | |||
| 27 | /** @var string */ |
||
| 28 | protected $cacheDir; |
||
| 29 | |||
| 30 | /** @var int */ |
||
| 31 | protected $duration; |
||
| 32 | |||
| 33 | public function __construct(Builder $builder, string $pool = '') |
||
| 38 | } |
||
| 39 | |||
| 40 | /** |
||
| 41 | * {@inheritdoc} |
||
| 42 | */ |
||
| 43 | public function set($key, $value, $ttl = null): bool |
||
| 44 | { |
||
| 45 | try { |
||
| 46 | $key = self::sanitizeKey($key); |
||
| 47 | $this->prune($key); |
||
| 48 | // put file content in a dedicated file |
||
| 49 | if (\is_array($value) && !empty($value['content']) && !empty($value['path'])) { |
||
| 50 | Util\File::getFS()->dumpFile($this->getContentFilePathname($value['path']), $value['content']); |
||
| 51 | unset($value['content']); |
||
| 52 | } |
||
| 53 | // serialize data |
||
| 54 | $data = serialize([ |
||
| 55 | 'value' => $value, |
||
| 56 | 'expiration' => time() + $this->duration($ttl), |
||
| 57 | ]); |
||
| 58 | Util\File::getFS()->dumpFile($this->getFilePathname($key), $data); |
||
| 59 | } catch (\Exception $e) { |
||
| 60 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 61 | |||
| 62 | return false; |
||
| 63 | } |
||
| 64 | |||
| 65 | return true; |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * {@inheritdoc} |
||
| 70 | */ |
||
| 71 | public function has($key): bool |
||
| 72 | { |
||
| 73 | $key = self::sanitizeKey($key); |
||
| 74 | if (!Util\File::getFS()->exists($this->getFilePathname($key))) { |
||
| 75 | return false; |
||
| 76 | } |
||
| 77 | |||
| 78 | return true; |
||
| 79 | } |
||
| 80 | |||
| 81 | /** |
||
| 82 | * {@inheritdoc} |
||
| 83 | */ |
||
| 84 | public function get($key, $default = null): mixed |
||
| 85 | { |
||
| 86 | try { |
||
| 87 | $key = self::sanitizeKey($key); |
||
| 88 | // return default value if file doesn't exists |
||
| 89 | if (false === $content = Util\File::fileGetContents($this->getFilePathname($key))) { |
||
| 90 | return $default; |
||
| 91 | } |
||
| 92 | // unserialize data |
||
| 93 | $data = unserialize($content); |
||
| 94 | // check expiration |
||
| 95 | if ($data['expiration'] <= time()) { |
||
| 96 | $this->delete($key); |
||
| 97 | |||
| 98 | return $default; |
||
| 99 | } |
||
| 100 | // get content from dedicated file |
||
| 101 | if (\is_array($data['value']) && isset($data['value']['path'])) { |
||
| 102 | if (false !== $content = Util\File::fileGetContents($this->getContentFilePathname($data['value']['path']))) { |
||
| 103 | $data['value']['content'] = $content; |
||
| 104 | } |
||
| 105 | } |
||
| 106 | } catch (\Exception $e) { |
||
| 107 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 108 | |||
| 109 | return $default; |
||
| 110 | } |
||
| 111 | |||
| 112 | return $data['value']; |
||
| 113 | } |
||
| 114 | |||
| 115 | /** |
||
| 116 | * {@inheritdoc} |
||
| 117 | */ |
||
| 118 | public function delete($key): bool |
||
| 131 | } |
||
| 132 | |||
| 133 | /** |
||
| 134 | * {@inheritdoc} |
||
| 135 | */ |
||
| 136 | public function clear(): bool |
||
| 137 | { |
||
| 138 | try { |
||
| 139 | Util\File::getFS()->remove($this->cacheDir); |
||
| 140 | } catch (\Exception $e) { |
||
| 141 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 142 | |||
| 143 | return false; |
||
| 144 | } |
||
| 145 | |||
| 146 | return true; |
||
| 147 | } |
||
| 148 | |||
| 149 | /** |
||
| 150 | * {@inheritdoc} |
||
| 151 | */ |
||
| 152 | public function getMultiple($keys, $default = null): iterable |
||
| 155 | } |
||
| 156 | |||
| 157 | /** |
||
| 158 | * {@inheritdoc} |
||
| 159 | */ |
||
| 160 | public function setMultiple($values, $ttl = null): bool |
||
| 161 | { |
||
| 162 | throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__)); |
||
| 163 | } |
||
| 164 | |||
| 165 | /** |
||
| 166 | * {@inheritdoc} |
||
| 167 | */ |
||
| 168 | public function deleteMultiple($keys): bool |
||
| 171 | } |
||
| 172 | |||
| 173 | /** |
||
| 174 | * Creates key from a string: "$name|uniqid__HASH__VERSION". |
||
| 175 | * $name is optional to add a human readable name to the key. |
||
| 176 | */ |
||
| 177 | public function createKey(?string $name, string $value): string |
||
| 178 | { |
||
| 179 | $hash = hash('md5', $value); |
||
| 180 | $name = $name ? self::sanitizeKey($name) : $hash; |
||
| 181 | |||
| 182 | return \sprintf('%s__%s__%s', $name, $hash, $this->builder->getVersion()); |
||
| 183 | } |
||
| 184 | |||
| 185 | /** |
||
| 186 | * Creates key from an Asset: "$path_$ext_$tags__HASH__VERSION". |
||
| 187 | */ |
||
| 188 | public function createKeyFromAsset(Asset $asset, ?array $tags = null): string |
||
| 189 | { |
||
| 190 | $tags = implode('_', $tags ?? []); |
||
| 191 | $name = "{$asset['path']}_{$asset['ext']}" . ($tags ? "_$tags" : ''); |
||
| 192 | |||
| 193 | return $this->createKey($name, $asset['content']); |
||
|
|
|||
| 194 | } |
||
| 195 | |||
| 196 | /** |
||
| 197 | * Creates key from a file: "RelativePathname__MD5". |
||
| 198 | * |
||
| 199 | * @throws RuntimeException |
||
| 200 | */ |
||
| 201 | public function createKeyFromFile(\Symfony\Component\Finder\SplFileInfo $file): string |
||
| 202 | { |
||
| 203 | if (false === $content = Util\File::fileGetContents($file->getRealPath())) { |
||
| 204 | throw new RuntimeException(\sprintf('Can\'t create cache key for "%s".', $file)); |
||
| 205 | } |
||
| 206 | |||
| 207 | return $this->createKey($file->getRelativePathname(), $content); |
||
| 208 | } |
||
| 209 | |||
| 210 | /** |
||
| 211 | * Clear cache by pattern. |
||
| 212 | */ |
||
| 213 | public function clearByPattern(string $pattern): int |
||
| 214 | { |
||
| 215 | try { |
||
| 216 | if (!Util\File::getFS()->exists($this->cacheDir)) { |
||
| 217 | throw new RuntimeException(\sprintf('The cache directory "%s" does not exists.', $this->cacheDir)); |
||
| 218 | } |
||
| 219 | $fileCount = 0; |
||
| 220 | $iterator = new \RecursiveIteratorIterator( |
||
| 221 | new \RecursiveDirectoryIterator($this->cacheDir), |
||
| 222 | \RecursiveIteratorIterator::SELF_FIRST |
||
| 223 | ); |
||
| 224 | foreach ($iterator as $file) { |
||
| 225 | if ($file->isFile()) { |
||
| 226 | if (preg_match('/' . $pattern . '/i', $file->getPathname())) { |
||
| 227 | Util\File::getFS()->remove($file->getPathname()); |
||
| 228 | $fileCount++; |
||
| 229 | $this->builder->getLogger()->debug(\sprintf('Cache removed: "%s"', Util\File::getFS()->makePathRelative($file->getPathname(), $this->builder->getConfig()->getCachePath()))); |
||
| 230 | } |
||
| 231 | } |
||
| 232 | } |
||
| 233 | } catch (\Exception $e) { |
||
| 234 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 235 | |||
| 236 | return 0; |
||
| 237 | } |
||
| 238 | |||
| 239 | return $fileCount; |
||
| 240 | } |
||
| 241 | |||
| 242 | /** |
||
| 243 | * Returns cache content file pathname from path. |
||
| 244 | */ |
||
| 245 | public function getContentFilePathname(string $path): string |
||
| 246 | { |
||
| 247 | $path = str_replace(['https://', 'http://'], '', $path); // remove protocol (if URL) |
||
| 248 | |||
| 249 | return Util::joinFile($this->cacheDir, 'files', $path); |
||
| 250 | } |
||
| 251 | |||
| 252 | /** |
||
| 253 | * Returns cache file pathname from key. |
||
| 254 | */ |
||
| 255 | private function getFilePathname(string $key): string |
||
| 256 | { |
||
| 257 | return Util::joinFile($this->cacheDir, "$key.ser"); |
||
| 258 | } |
||
| 259 | |||
| 260 | /** |
||
| 261 | * Prepares and validate $key. |
||
| 262 | */ |
||
| 263 | public static function sanitizeKey(string $key): string |
||
| 264 | { |
||
| 265 | $key = str_replace(['https://', 'http://'], '', $key); // remove protocol (if URL) |
||
| 266 | $key = Page::slugify($key); // slugify |
||
| 267 | $key = trim($key, '/'); // remove leading/trailing slashes |
||
| 268 | $key = str_replace(['\\', '/'], ['-', '-'], $key); // replace slashes by hyphens |
||
| 269 | $key = substr($key, 0, 200); // truncate to 200 characters (NTFS filename length limit is 255 characters) |
||
| 270 | |||
| 271 | return $key; |
||
| 272 | } |
||
| 273 | |||
| 274 | /** |
||
| 275 | * Removes previous cache files. |
||
| 276 | */ |
||
| 277 | private function prune(string $key): bool |
||
| 278 | { |
||
| 279 | try { |
||
| 280 | $keyAsArray = explode('__', self::sanitizeKey($key)); |
||
| 281 | // if 3 parts (with hash), remove all files with the same first part |
||
| 282 | // pattern: `path_tag__hash__version` |
||
| 283 | if (!empty($keyAsArray[0]) && \count($keyAsArray) == 3) { |
||
| 284 | $pattern = Util::joinFile($this->cacheDir, $keyAsArray[0]) . '*'; |
||
| 285 | foreach (glob($pattern) ?: [] as $filename) { |
||
| 286 | Util\File::getFS()->remove($filename); |
||
| 287 | $this->builder->getLogger()->debug(\sprintf('Cache removed: "%s"', Util\File::getFS()->makePathRelative($filename, $this->builder->getConfig()->getCachePath()))); |
||
| 288 | } |
||
| 289 | } |
||
| 290 | } catch (\Exception $e) { |
||
| 291 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 292 | |||
| 293 | return false; |
||
| 294 | } |
||
| 295 | |||
| 296 | return true; |
||
| 297 | } |
||
| 298 | |||
| 299 | /** |
||
| 300 | * Convert the various expressions of a TTL value into duration in seconds. |
||
| 301 | */ |
||
| 302 | protected function duration(\DateInterval|int|null $ttl): int |
||
| 315 | } |
||
| 316 | } |
||
| 317 |