Passed
Push — configuration ( 81f61b...8ed840 )
by Arnaud
03:51
created

Cache   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 315
Duplicated Lines 0 %

Test Coverage

Coverage 60.15%

Importance

Changes 19
Bugs 1 Features 1
Metric Value
eloc 125
c 19
b 1
f 1
dl 0
loc 315
ccs 80
cts 133
cp 0.6015
rs 6.96
wmc 53

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A delete() 0 13 2
A getMultiple() 0 3 1
A deleteMultiple() 0 3 1
A setMultiple() 0 3 1
A clear() 0 11 2
A set() 0 23 5
A has() 0 8 2
B get() 0 29 7
A createKey() 0 6 2
A clearByPattern() 0 27 6
A sanitizeKey() 0 9 1
B createKeyFromAsset() 0 28 8
A getContentFilePathname() 0 5 1
A prune() 0 20 6
A getFilePathname() 0 3 1
A duration() 0 13 4
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
    /** @var int */
31
    protected $duration;
32
33 1
    public function __construct(Builder $builder, string $pool = '')
34
    {
35 1
        $this->builder = $builder;
36 1
        $this->cacheDir = Util::joinFile($builder->getConfig()->getCachePath(), $pool);
37 1
        $this->duration = 31536000; // 1 year
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 1
    public function set($key, $value, $ttl = null): bool
44
    {
45
        try {
46 1
            $key = self::sanitizeKey($key);
47 1
            $this->prune($key);
48
            // put file content in a dedicated file
49 1
            if (\is_array($value) && !empty($value['content']) && !empty($value['path'])) {
50 1
                Util\File::getFS()->dumpFile($this->getContentFilePathname($value['path']), $value['content']);
51 1
                unset($value['content']);
52
            }
53
            // serialize data
54 1
            $data = serialize([
55 1
                'value'      => $value,
56 1
                'expiration' => time() + $this->duration($ttl),
57 1
            ]);
58 1
            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 1
        return true;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 1
    public function has($key): bool
72
    {
73 1
        $key = self::sanitizeKey($key);
74 1
        if (!Util\File::getFS()->exists($this->getFilePathname($key))) {
75 1
            return false;
76
        }
77
78 1
        return true;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84 1
    public function get($key, $default = null): mixed
85
    {
86
        try {
87 1
            $key = self::sanitizeKey($key);
88
            // return default value if file doesn't exists
89 1
            if (false === $content = Util\File::fileGetContents($this->getFilePathname($key))) {
90
                return $default;
91
            }
92
            // unserialize data
93 1
            $data = unserialize($content);
94
            // check expiration
95 1
            if ($data['expiration'] <= time()) {
96
                $this->delete($key);
97
98
                return $default;
99
            }
100
            // get content from dedicated file
101 1
            if (\is_array($data['value']) && isset($data['value']['path'])) {
102 1
                if (false !== $content = Util\File::fileGetContents($this->getContentFilePathname($data['value']['path']))) {
103 1
                    $data['value']['content'] = $content;
104
                }
105
            }
106
        } catch (\Exception $e) {
107
            $this->builder->getLogger()->error($e->getMessage());
108
109
            return $default;
110
        }
111
112 1
        return $data['value'];
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function delete($key): bool
119
    {
120
        try {
121
            $key = self::sanitizeKey($key);
122
            Util\File::getFS()->remove($this->getFilePathname($key));
123
            $this->prune($key);
124
        } catch (\Exception $e) {
125
            $this->builder->getLogger()->error($e->getMessage());
126
127
            return false;
128
        }
129
130
        return true;
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
153
    {
154
        throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__));
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
169
    {
170
        throw new \Exception(\sprintf('%s::%s not yet implemented.', __CLASS__, __FUNCTION__));
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 1
    public function createKey(?string $name, string $value): string
178
    {
179 1
        $hash = hash('md5', $value);
180 1
        $name = $name ? self::sanitizeKey($name) : $hash;
181
182 1
        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 1
    public function createKeyFromAsset(Asset $asset, ?array $tags = null): string
189
    {
190 1
        $t = $tags;
191 1
        $tags = [];
192 1
193 1
        if ($t !== null) {
194 1
            ksort($t);
195 1
            foreach ($t as $key => $value) {
196 1
                switch (\gettype($value)) {
197
                    case 'boolean':
198 1
                        if ($value === true) {
199 1
                            $tags[] = $key;
200 1
                        }
201 1
                        break;
202 1
                    case 'string':
203
                    case 'integer':
204 1
                        if (!empty($value)) {
205
                            $tags[] = substr($key, 0, 1) . $value;
206
                        }
207 1
                        break;
208 1
                }
209
            }
210 1
        }
211
212
        $tagsInline = implode('_', $tags);
213
        $name = "{$asset['_path']}_{$asset['ext']}_$tagsInline";
214
215
        return $this->createKey($name, $asset['content'] ?? '');
216
    }
217
218 1
    /**
219
     * Creates key from a file: "RelativePathname__MD5".
220 1
     *
221
     * @throws RuntimeException
222
     */
223
    public function createKeyFromFile(\Symfony\Component\Finder\SplFileInfo $file): string
224 1
    {
225
        if (false === $content = Util\File::fileGetContents($file->getRealPath())) {
226
            throw new RuntimeException(\sprintf('Can\'t create cache key for "%s".', $file));
227
        }
228
229
        return $this->createKey($file->getRelativePathname(), $content);
230
    }
231
232
    /**
233
     * Clear cache by pattern.
234
     */
235
    public function clearByPattern(string $pattern): int
236
    {
237
        try {
238
            if (!Util\File::getFS()->exists($this->cacheDir)) {
239
                throw new RuntimeException(\sprintf('The cache directory "%s" does not exists.', $this->cacheDir));
240
            }
241
            $fileCount = 0;
242
            $iterator = new \RecursiveIteratorIterator(
243
                new \RecursiveDirectoryIterator($this->cacheDir),
244
                \RecursiveIteratorIterator::SELF_FIRST
245
            );
246
            foreach ($iterator as $file) {
247
                if ($file->isFile()) {
248
                    if (preg_match('/' . $pattern . '/i', $file->getPathname())) {
249
                        Util\File::getFS()->remove($file->getPathname());
250
                        $fileCount++;
251
                        $this->builder->getLogger()->debug(\sprintf('Cache removed: "%s"', Util\File::getFS()->makePathRelative($file->getPathname(), $this->builder->getConfig()->getCachePath())));
252
                    }
253
                }
254
            }
255
        } catch (\Exception $e) {
256
            $this->builder->getLogger()->error($e->getMessage());
257
258
            return 0;
259
        }
260
261
        return $fileCount;
262 1
    }
263
264 1
    /**
265
     * Returns cache content file pathname from path.
266 1
     */
267
    public function getContentFilePathname(string $path): string
268
    {
269
        $path = str_replace(['https://', 'http://'], '', $path); // remove protocol (if URL)
270
271
        return Util::joinFile($this->cacheDir, 'files', $path);
272 1
    }
273
274 1
    /**
275
     * Returns cache file pathname from key.
276
     */
277
    private function getFilePathname(string $key): string
278
    {
279
        return Util::joinFile($this->cacheDir, "$key.ser");
280 1
    }
281
282 1
    /**
283 1
     * Prepares and validate $key.
284 1
     */
285 1
    public static function sanitizeKey(string $key): string
286 1
    {
287
        $key = str_replace(['https://', 'http://'], '', $key); // remove protocol (if URL)
288 1
        $key = Page::slugify($key);                            // slugify
289
        $key = trim($key, '/');                                // remove leading/trailing slashes
290
        $key = str_replace(['\\', '/'], ['-', '-'], $key);     // replace slashes by hyphens
291
        $key = substr($key, 0, 200);                           // truncate to 200 characters (NTFS filename length limit is 255 characters)
292
293
        return $key;
294 1
    }
295
296
    /**
297 1
     * Removes previous cache files.
298
     */
299
    private function prune(string $key): bool
300 1
    {
301 1
        try {
302 1
            $keyAsArray = explode('__', self::sanitizeKey($key));
303 1
            // if 2 or more parts (with hash), remove all files with the same first part
304 1
            // pattern: `name__hash__version`
305
            if (!empty($keyAsArray[0]) && \count($keyAsArray) >= 2) {
306
                $pattern = Util::joinFile($this->cacheDir, $keyAsArray[0]) . '*';
307
                foreach (glob($pattern) ?: [] as $filename) {
308
                    Util\File::getFS()->remove($filename);
309
                    $this->builder->getLogger()->debug(\sprintf('Cache removed: "%s"', Util\File::getFS()->makePathRelative($filename, $this->builder->getConfig()->getCachePath())));
310
                }
311
            }
312
        } catch (\Exception $e) {
313 1
            $this->builder->getLogger()->error($e->getMessage());
314
315
            return false;
316
        }
317
318
        return true;
319 1
    }
320
321 1
    /**
322 1
     * Convert the various expressions of a TTL value into duration in seconds.
323
     */
324 1
    protected function duration(\DateInterval|int|null $ttl): int
325
    {
326
        if ($ttl === null) {
327 1
            return $this->duration;
328 1
        }
329
        if (\is_int($ttl)) {
330
            return $ttl;
331
        }
332
        if ($ttl instanceof \DateInterval) {
333
            return (int) $ttl->d * 86400 + $ttl->h * 3600 + $ttl->i * 60 + $ttl->s;
334
        }
335
336
        throw new \InvalidArgumentException('TTL values must be one of null, int, \DateInterval');
337
    }
338
}
339