| Total Complexity | 42 |
| Total Lines | 248 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like FileCache 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 FileCache, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 17 | final class FileCache extends SimpleCache |
||
| 18 | { |
||
| 19 | private const TTL_INFINITY = 31536000; // 1 year |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var string the directory to store cache files. You may use [path alias](guide:concept-aliases) here. |
||
| 23 | */ |
||
| 24 | private $cachePath; |
||
| 25 | /** |
||
| 26 | * @var string cache file suffix. Defaults to '.bin'. |
||
| 27 | */ |
||
| 28 | private $cacheFileSuffix = '.bin'; |
||
| 29 | /** |
||
| 30 | * @var int the level of sub-directories to store cache files. Defaults to 1. |
||
| 31 | * If the system has huge number of cache files (e.g. one million), you may use a bigger value |
||
| 32 | * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system |
||
| 33 | * is not over burdened with a single directory having too many files. |
||
| 34 | */ |
||
| 35 | private $directoryLevel = 1; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * @var int the probability (parts per million) that garbage collection (GC) should be performed |
||
| 39 | * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance. |
||
| 40 | * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all. |
||
| 41 | */ |
||
| 42 | private $gcProbability = 10; |
||
| 43 | /** |
||
| 44 | * @var int the permission to be set for newly created cache files. |
||
| 45 | * This value will be used by PHP chmod() function. No umask will be applied. |
||
| 46 | * If not set, the permission will be determined by the current environment. |
||
| 47 | */ |
||
| 48 | private $fileMode; |
||
| 49 | /** |
||
| 50 | * @var int the permission to be set for newly created directories. |
||
| 51 | * This value will be used by PHP chmod() function. No umask will be applied. |
||
| 52 | * Defaults to 0775, meaning the directory is read-writable by owner and group, |
||
| 53 | * but read-only for other users. |
||
| 54 | */ |
||
| 55 | private $dirMode = 0775; |
||
| 56 | |||
| 57 | private $logger; |
||
| 58 | |||
| 59 | public function __construct(string $cachePath, LoggerInterface $logger, SerializerInterface $serializer = null) |
||
| 60 | { |
||
| 61 | $this->logger = $logger; |
||
| 62 | $this->setCachePath($cachePath); |
||
| 63 | parent::__construct($serializer); |
||
| 64 | } |
||
| 65 | |||
| 66 | /** |
||
| 67 | * Sets cache path and ensures it exists. |
||
| 68 | * @param string $cachePath |
||
| 69 | */ |
||
| 70 | public function setCachePath(string $cachePath): void |
||
| 71 | { |
||
| 72 | $this->cachePath = $cachePath; |
||
| 73 | |||
| 74 | if (!$this->createDirectory($this->cachePath, $this->dirMode)) { |
||
| 75 | throw new CacheException('Failed to create cache directory "' . $this->cachePath . '"'); |
||
| 76 | } |
||
| 77 | } |
||
| 78 | |||
| 79 | protected function hasValue(string $key): bool |
||
| 80 | { |
||
| 81 | $cacheFile = $this->getCacheFile($key); |
||
| 82 | |||
| 83 | return @filemtime($cacheFile) > time(); |
||
| 84 | } |
||
| 85 | |||
| 86 | /** |
||
| 87 | * @param string $cacheFileSuffix cache file suffix. Defaults to '.bin'. |
||
| 88 | */ |
||
| 89 | public function setCacheFileSuffix(string $cacheFileSuffix): void |
||
| 90 | { |
||
| 91 | $this->cacheFileSuffix = $cacheFileSuffix; |
||
| 92 | } |
||
| 93 | |||
| 94 | /** |
||
| 95 | * @param int $gcProbability the probability (parts per million) that garbage collection (GC) should be performed |
||
| 96 | * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance. |
||
| 97 | * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all. |
||
| 98 | */ |
||
| 99 | public function setGcProbability(int $gcProbability): void |
||
| 100 | { |
||
| 101 | $this->gcProbability = $gcProbability; |
||
| 102 | } |
||
| 103 | |||
| 104 | /** |
||
| 105 | * @param int $fileMode the permission to be set for newly created cache files. |
||
| 106 | * This value will be used by PHP chmod() function. No umask will be applied. |
||
| 107 | * If not set, the permission will be determined by the current environment. |
||
| 108 | */ |
||
| 109 | public function setFileMode(int $fileMode): void |
||
| 112 | } |
||
| 113 | |||
| 114 | /** |
||
| 115 | * @param int $dirMode the permission to be set for newly created directories. |
||
| 116 | * This value will be used by PHP chmod() function. No umask will be applied. |
||
| 117 | * Defaults to 0775, meaning the directory is read-writable by owner and group, |
||
| 118 | * but read-only for other users. |
||
| 119 | */ |
||
| 120 | public function setDirMode(int $dirMode): void |
||
| 121 | { |
||
| 122 | $this->dirMode = $dirMode; |
||
| 123 | } |
||
| 124 | |||
| 125 | protected function getValue(string $key, $default = null) |
||
| 126 | { |
||
| 127 | $cacheFile = $this->getCacheFile($key); |
||
| 128 | |||
| 129 | if (@filemtime($cacheFile) > time()) { |
||
| 130 | $fp = @fopen($cacheFile, 'rb'); |
||
| 131 | if ($fp !== false) { |
||
| 132 | @flock($fp, LOCK_SH); |
||
|
|
|||
| 133 | $cacheValue = @stream_get_contents($fp); |
||
| 134 | @flock($fp, LOCK_UN); |
||
| 135 | @fclose($fp); |
||
| 136 | return $cacheValue; |
||
| 137 | } |
||
| 138 | } |
||
| 139 | |||
| 140 | return $default; |
||
| 141 | } |
||
| 142 | |||
| 143 | protected function setValue(string $key, $value, ?int $ttl): bool |
||
| 144 | { |
||
| 145 | $this->gc(); |
||
| 146 | $cacheFile = $this->getCacheFile($key); |
||
| 147 | if ($this->directoryLevel > 0) { |
||
| 148 | $directoryName = \dirname($cacheFile); |
||
| 149 | if (!$this->createDirectory($directoryName, $this->dirMode)) { |
||
| 150 | $this->logger->warning('Failed to create cache directory "' . $directoryName . '"'); |
||
| 151 | return false; |
||
| 152 | } |
||
| 153 | } |
||
| 154 | // If ownership differs the touch call will fail, so we try to |
||
| 155 | // rebuild the file from scratch by deleting it first |
||
| 156 | // https://github.com/yiisoft/yii2/pull/16120 |
||
| 157 | if (\function_exists('posix_geteuid') && is_file($cacheFile) && fileowner($cacheFile) !== posix_geteuid()) { |
||
| 158 | @unlink($cacheFile); |
||
| 159 | } |
||
| 160 | |||
| 161 | if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) { |
||
| 162 | if ($this->fileMode !== null) { |
||
| 163 | @chmod($cacheFile, $this->fileMode); |
||
| 164 | } |
||
| 165 | $ttl = $ttl ?? self::TTL_INFINITY; |
||
| 166 | return @touch($cacheFile, $ttl + time()); |
||
| 167 | } |
||
| 168 | |||
| 169 | $error = error_get_last(); |
||
| 170 | $this->logger->warning("Failed to write cache data to \"$cacheFile\": " . $error['message']); |
||
| 171 | return false; |
||
| 172 | } |
||
| 173 | |||
| 174 | protected function deleteValue(string $key): bool |
||
| 175 | { |
||
| 176 | $cacheFile = $this->getCacheFile($key); |
||
| 177 | return @unlink($cacheFile); |
||
| 178 | } |
||
| 179 | |||
| 180 | /** |
||
| 181 | * Returns the cache file path given the cache key. |
||
| 182 | * @param string $key cache key |
||
| 183 | * @return string the cache file path |
||
| 184 | */ |
||
| 185 | private function getCacheFile(string $key): string |
||
| 199 | } |
||
| 200 | |||
| 201 | public function clear(): bool |
||
| 202 | { |
||
| 203 | $this->removeCacheFiles($this->cachePath, false); |
||
| 204 | return true; |
||
| 205 | } |
||
| 206 | |||
| 207 | /** |
||
| 208 | * Removes expired cache files |
||
| 209 | * @throws \Exception |
||
| 210 | */ |
||
| 211 | public function gc(): void |
||
| 212 | { |
||
| 213 | if (\random_int(0, 1000000) < $this->gcProbability) { |
||
| 214 | $this->removeCacheFiles($this->cachePath, true); |
||
| 215 | } |
||
| 216 | } |
||
| 217 | |||
| 218 | /** |
||
| 219 | * Recursively removing expired cache files under a directory. |
||
| 220 | * This method is mainly used by {@see gc()}. |
||
| 221 | * @param string $path the directory under which expired cache files are removed. |
||
| 222 | * @param bool $expiredOnly whether to only remove expired cache files. If false, all files |
||
| 223 | * under `$path` will be removed. |
||
| 224 | */ |
||
| 225 | private function removeCacheFiles(string $path, bool $expiredOnly): void |
||
| 226 | { |
||
| 227 | if (($handle = opendir($path)) !== false) { |
||
| 228 | while (($file = readdir($handle)) !== false) { |
||
| 229 | if (strncmp($file, '.', 1) === 0) { |
||
| 230 | continue; |
||
| 231 | } |
||
| 232 | $fullPath = $path . DIRECTORY_SEPARATOR . $file; |
||
| 233 | if (is_dir($fullPath)) { |
||
| 234 | $this->removeCacheFiles($fullPath, $expiredOnly); |
||
| 235 | if (!$expiredOnly && !@rmdir($fullPath)) { |
||
| 236 | $error = error_get_last(); |
||
| 237 | throw new CacheException("Unable to remove directory '{$fullPath}': {$error['message']}"); |
||
| 238 | } |
||
| 239 | } elseif (!$expiredOnly || ($expiredOnly && @filemtime($fullPath) < time())) { |
||
| 240 | if (!@unlink($fullPath)) { |
||
| 241 | $error = error_get_last(); |
||
| 242 | throw new CacheException("Unable to remove file '{$fullPath}': {$error['message']}"); |
||
| 243 | } |
||
| 244 | } |
||
| 245 | } |
||
| 246 | closedir($handle); |
||
| 247 | } |
||
| 248 | } |
||
| 249 | |||
| 250 | private function createDirectory(string $path, int $mode): bool |
||
| 251 | { |
||
| 252 | return is_dir($path) || (mkdir($path, $mode, true) && is_dir($path)); |
||
| 253 | } |
||
| 254 | |||
| 255 | /** |
||
| 256 | * @param int $directoryLevel the level of sub-directories to store cache files. Defaults to 1. |
||
| 257 | * If the system has huge number of cache files (e.g. one million), you may use a bigger value |
||
| 258 | * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system |
||
| 259 | * is not over burdened with a single directory having too many files. |
||
| 260 | * |
||
| 261 | */ |
||
| 262 | public function setDirectoryLevel(int $directoryLevel): void |
||
| 265 | } |
||
| 266 | } |
||
| 267 |
If you suppress an error, we recommend checking for the error condition explicitly: