Passed
Push — master ( e556bd...439087 )
by
unknown
05:03
created

Cache   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 329
Duplicated Lines 0 %

Test Coverage

Coverage 54.67%

Importance

Changes 12
Bugs 1 Features 1
Metric Value
eloc 128
c 12
b 1
f 1
dl 0
loc 329
ccs 76
cts 139
cp 0.5467
rs 4.5599
wmc 58

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A clearByPattern() 0 27 6
A createKey() 0 6 2
A sanitizeKey() 0 9 1
B createKeyFromAsset() 0 27 8
A delete() 0 13 2
A set() 0 23 6
A getContentFilePathname() 0 5 1
A has() 0 8 2
A prune() 0 19 6
A getFilePathname() 0 3 1
A getMultiple() 0 3 1
A duration() 0 10 3
B get() 0 36 10
A deleteMultiple() 0 3 1
A deleteContentFile() 0 11 2
A setMultiple() 0 3 1
A clear() 0 11 2
A createKeyFromFile() 0 7 2

How to fix   Complexity   

Complex Class

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
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Assets;
15
16
use Cecil\Builder;
17
use Cecil\Collection\Page\Page;
18
use Cecil\Exception\RuntimeException;
19
use Cecil\Util;
20
use Psr\SimpleCache\CacheInterface;
21
22
class Cache implements CacheInterface
23
{
24
    /** @var Builder */
25
    protected $builder;
26
27
    /** @var string */
28
    protected $cacheDir;
29
30 1
    public function __construct(Builder $builder, string $pool = '')
31
    {
32 1
        $this->builder = $builder;
33 1
        $this->cacheDir = Util::joinFile($builder->getConfig()->getCachePath(), $pool);
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 1
    public function set($key, $value, $ttl = null): bool
40
    {
41
        try {
42 1
            $key = self::sanitizeKey($key);
43 1
            $this->prune($key);
44
            // put file content in a dedicated file
45 1
            if (\is_array($value) && !empty($value['content']) && !empty($value['path'])) {
46 1
                Util\File::getFS()->dumpFile($this->getContentFilePathname($value['path']), $value['content']);
47 1
                unset($value['content']);
48
            }
49
            // serialize data
50 1
            $data = serialize([
51 1
                'value'      => $value,
52 1
                'expiration' => $ttl === null ? null : time() + $this->duration($ttl),
53 1
            ]);
54 1
            Util\File::getFS()->dumpFile($this->getFilePathname($key), $data);
55
        } catch (\Exception $e) {
56
            $this->builder->getLogger()->error($e->getMessage());
57
58
            return false;
59
        }
60
61 1
        return true;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 1
    public function has($key): bool
68
    {
69 1
        $key = self::sanitizeKey($key);
70 1
        if (!Util\File::getFS()->exists($this->getFilePathname($key))) {
71 1
            return false;
72
        }
73
74 1
        return true;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 1
    public function get($key, $default = null): mixed
81
    {
82
        try {
83 1
            $key = self::sanitizeKey($key);
84
            // return default value if file doesn't exists
85 1
            if (false === $content = Util\File::fileGetContents($this->getFilePathname($key))) {
86
                return $default;
87
            }
88
            // unserialize data
89 1
            $data = unserialize($content);
90
            // check expiration
91 1
            if ($data['expiration'] !== null && $data['expiration'] <= time()) {
92
                $this->builder->getLogger()->debug(\sprintf('Cache expired: "%s"', $key));
93
                // remove expired cache
94
                if ($this->delete($key)) {
95
                    // remove content file if exists
96
                    if (!empty($data['value']['path'])) {
97
                        $this->deleteContentFile($data['value']['path']);
98
                    }
99
                }
100
101
                return $default;
102
            }
103
            // get content from dedicated file
104 1
            if (\is_array($data['value']) && isset($data['value']['path'])) {
105 1
                if (false !== $content = Util\File::fileGetContents($this->getContentFilePathname($data['value']['path']))) {
106 1
                    $data['value']['content'] = $content;
107
                }
108
            }
109
        } catch (\Exception $e) {
110
            $this->builder->getLogger()->error($e->getMessage());
111
112
            return $default;
113
        }
114
115 1
        return $data['value'];
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121
    public function delete($key): bool
122
    {
123
        try {
124
            $key = self::sanitizeKey($key);
125
            Util\File::getFS()->remove($this->getFilePathname($key));
126
            $this->prune($key);
127
        } catch (\Exception $e) {
128
            $this->builder->getLogger()->error($e->getMessage());
129
130
            return false;
131
        }
132
133
        return true;
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    public function clear(): bool
140
    {
141
        try {
142
            Util\File::getFS()->remove($this->cacheDir);
143
        } catch (\Exception $e) {
144
            $this->builder->getLogger()->error($e->getMessage());
145
146
            return false;
147
        }
148
149
        return true;
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155
    public function getMultiple($keys, $default = null): iterable
156
    {
157
        throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__));
158
    }
159
160
    /**
161
     * {@inheritdoc}
162
     */
163
    public function setMultiple($values, $ttl = null): bool
164
    {
165
        throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__));
166
    }
167
168
    /**
169
     * {@inheritdoc}
170
     */
171
    public function deleteMultiple($keys): bool
172
    {
173
        throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__));
174
    }
175
176
    /**
177
     * Creates key from a string: "$name|uniqid__HASH__VERSION".
178
     * $name is optional to add a human readable name to the key.
179
     */
180 1
    public function createKey(?string $name, string $value): string
181
    {
182 1
        $hash = hash('md5', $value);
183 1
        $name = $name ? self::sanitizeKey($name) : $hash;
184
185 1
        return \sprintf('%s__%s__%s', $name, $hash, $this->builder->getVersion());
186
    }
187
188
    /**
189
     * Creates key from an Asset: "$path_$ext_$tags__HASH__VERSION".
190
     */
191 1
    public function createKeyFromAsset(Asset $asset, ?array $tags = null): string
192
    {
193 1
        $t = $tags;
194 1
        $tags = [];
195
196 1
        if ($t !== null) {
197 1
            foreach ($t as $key => $value) {
198 1
                switch (\gettype($value)) {
199 1
                    case 'boolean':
200 1
                        if ($value === true) {
201 1
                            $tags[] = $key;
202
                        }
203 1
                        break;
204 1
                    case 'string':
205 1
                    case 'integer':
206 1
                        if (!empty($value)) {
207 1
                            $tags[] = substr($key, 0, 1) . $value;
208
                        }
209 1
                        break;
210
                }
211
            }
212
        }
213
214 1
        $tagsInline = implode('_', str_replace('_', '', $tags));
215 1
        $name = "{$asset['_path']}_{$asset['ext']}_$tagsInline";
216
217 1
        return $this->createKey($name, $asset['content'] ?? '');
218
    }
219
220
    /**
221
     * Creates key from a file: "RelativePathname__MD5".
222
     *
223
     * @throws RuntimeException
224
     */
225 1
    public function createKeyFromFile(\Symfony\Component\Finder\SplFileInfo $file): string
226
    {
227 1
        if (false === $content = Util\File::fileGetContents($file->getRealPath())) {
228
            throw new RuntimeException(\sprintf('Can\'t create cache key for "%s".', $file));
229
        }
230
231 1
        return $this->createKey($file->getRelativePathname(), $content);
232
    }
233
234
    /**
235
     * Clear cache by pattern.
236
     */
237
    public function clearByPattern(string $pattern): int
238
    {
239
        try {
240
            if (!Util\File::getFS()->exists($this->cacheDir)) {
241
                throw new RuntimeException(\sprintf('The cache directory "%s" does not exists.', $this->cacheDir));
242
            }
243
            $fileCount = 0;
244
            $iterator = new \RecursiveIteratorIterator(
245
                new \RecursiveDirectoryIterator($this->cacheDir),
246
                \RecursiveIteratorIterator::SELF_FIRST
247
            );
248
            foreach ($iterator as $file) {
249
                if ($file->isFile()) {
250
                    if (preg_match('/' . $pattern . '/i', $file->getPathname())) {
251
                        Util\File::getFS()->remove($file->getPathname());
252
                        $fileCount++;
253
                        $this->builder->getLogger()->debug(\sprintf('Cache removed: "%s"', Util\File::getFS()->makePathRelative($file->getPathname(), $this->builder->getConfig()->getCachePath())));
254
                    }
255
                }
256
            }
257
        } catch (\Exception $e) {
258
            $this->builder->getLogger()->error($e->getMessage());
259
260
            return 0;
261
        }
262
263
        return $fileCount;
264
    }
265
266
    /**
267
     * Returns cache content file pathname from path.
268
     */
269 1
    public function getContentFilePathname(string $path): string
270
    {
271 1
        $path = str_replace(['https://', 'http://'], '', $path); // remove protocol (if URL)
272
273 1
        return Util::joinFile($this->cacheDir, 'files', $path);
274
    }
275
276
    /**
277
     * Returns cache file pathname from key.
278
     */
279 1
    private function getFilePathname(string $key): string
280
    {
281 1
        return Util::joinFile($this->cacheDir, "$key.ser");
282
    }
283
284
    /**
285
     * Prepares and validate $key.
286
     */
287 1
    public static function sanitizeKey(string $key): string
288
    {
289 1
        $key = str_replace(['https://', 'http://'], '', $key); // remove protocol (if URL)
290 1
        $key = Page::slugify($key);                            // slugify
291 1
        $key = trim($key, '/');                                // remove leading/trailing slashes
292 1
        $key = str_replace(['\\', '/'], ['-', '-'], $key);     // replace slashes by hyphens
293 1
        $key = substr($key, 0, 200);                           // truncate to 200 characters (NTFS filename length limit is 255 characters)
294
295 1
        return $key;
296
    }
297
298
    /**
299
     * Removes previous cache files.
300
     */
301 1
    private function prune(string $key): bool
302
    {
303
        try {
304 1
            $keyAsArray = explode('__', self::sanitizeKey($key));
305
            // if 2 or more parts (with hash), remove all files with the same first part
306
            // pattern: `name__hash__version`
307 1
            if (!empty($keyAsArray[0]) && \count($keyAsArray) >= 2) {
308 1
                $pattern = Util::joinFile($this->cacheDir, $keyAsArray[0]) . '*';
309 1
                foreach (glob($pattern) ?: [] as $filename) {
310 1
                    Util\File::getFS()->remove($filename);
311
                }
312
            }
313
        } catch (\Exception $e) {
314
            $this->builder->getLogger()->error($e->getMessage());
315
316
            return false;
317
        }
318
319 1
        return true;
320
    }
321
322
    /**
323
     * Convert the various expressions of a TTL value into duration in seconds.
324
     */
325 1
    protected function duration(int|\DateInterval $ttl): int
326
    {
327 1
        if (\is_int($ttl)) {
328 1
            return $ttl;
329
        }
330
        if ($ttl instanceof \DateInterval) {
331
            return (int) $ttl->d * 86400 + $ttl->h * 3600 + $ttl->i * 60 + $ttl->s;
332
        }
333
334
        throw new \InvalidArgumentException('TTL values must be int or \DateInterval');
335
    }
336
337
    /**
338
     * Removes the cache content file.
339
     */
340
    protected function deleteContentFile(string $path): bool
341
    {
342
        try {
343
            Util\File::getFS()->remove($this->getContentFilePathname($path));
344
        } catch (\Exception $e) {
345
            $this->builder->getLogger()->error($e->getMessage());
346
347
            return false;
348
        }
349
350
        return true;
351
    }
352
}
353