• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Cecilapp / Cecil / 15454176852

04 Jun 2025 10:34PM UTC coverage: 82.784% (-0.009%) from 82.793%
15454176852

push

github

ArnaudLigny
refactor: debug less verbose about cache

3116 of 3764 relevant lines covered (82.78%)

0.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

53.33
/src/Assets/Cache.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
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
    public function __construct(Builder $builder, string $pool = '')
31
    {
32
        $this->builder = $builder;
1✔
33
        $this->cacheDir = Util::joinFile($builder->getConfig()->getCachePath(), $pool);
1✔
34
    }
35

36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function set($key, $value, $ttl = null): bool
40
    {
41
        try {
42
            $key = self::sanitizeKey($key);
1✔
43
            $this->prune($key);
1✔
44
            // put file content in a dedicated file
45
            if (\is_array($value) && !empty($value['content']) && !empty($value['path'])) {
1✔
46
                Util\File::getFS()->dumpFile($this->getContentFilePathname($value['path']), $value['content']);
1✔
47
                unset($value['content']);
1✔
48
            }
49
            // serialize data
50
            $data = serialize([
1✔
51
                'value'      => $value,
1✔
52
                'expiration' => $ttl === null ? null : time() + $this->duration($ttl),
1✔
53
            ]);
1✔
54
            Util\File::getFS()->dumpFile($this->getFilePathname($key), $data);
1✔
55
        } catch (\Exception $e) {
×
56
            $this->builder->getLogger()->error($e->getMessage());
×
57

58
            return false;
×
59
        }
60

61
        return true;
1✔
62
    }
63

64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function has($key): bool
68
    {
69
        $key = self::sanitizeKey($key);
1✔
70
        if (!Util\File::getFS()->exists($this->getFilePathname($key))) {
1✔
71
            return false;
1✔
72
        }
73

74
        return true;
1✔
75
    }
76

77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function get($key, $default = null): mixed
81
    {
82
        try {
83
            $key = self::sanitizeKey($key);
1✔
84
            // return default value if file doesn't exists
85
            if (false === $content = Util\File::fileGetContents($this->getFilePathname($key))) {
1✔
86
                return $default;
×
87
            }
88
            // unserialize data
89
            $data = unserialize($content);
1✔
90
            // check expiration
91
            if ($data['expiration'] !== null && $data['expiration'] <= time()) {
1✔
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
            if (\is_array($data['value']) && isset($data['value']['path'])) {
1✔
105
                if (false !== $content = Util\File::fileGetContents($this->getContentFilePathname($data['value']['path']))) {
1✔
106
                    $data['value']['content'] = $content;
1✔
107
                }
108
            }
109
        } catch (\Exception $e) {
×
110
            $this->builder->getLogger()->error($e->getMessage());
×
111

112
            return $default;
×
113
        }
114

115
        return $data['value'];
1✔
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
    public function createKey(?string $name, string $value): string
181
    {
182
        $hash = hash('md5', $value);
1✔
183
        $name = $name ? self::sanitizeKey($name) : $hash;
1✔
184

185
        return \sprintf('%s__%s__%s', $name, $hash, $this->builder->getVersion());
1✔
186
    }
187

188
    /**
189
     * Creates key from an Asset: "$path_$ext_$tags__HASH__VERSION".
190
     */
191
    public function createKeyFromAsset(Asset $asset, ?array $tags = null): string
192
    {
193
        $t = $tags;
1✔
194
        $tags = [];
1✔
195

196
        if ($t !== null) {
1✔
197
            foreach ($t as $key => $value) {
1✔
198
                switch (\gettype($value)) {
1✔
199
                    case 'boolean':
1✔
200
                        if ($value === true) {
1✔
201
                            $tags[] = $key;
1✔
202
                        }
203
                        break;
1✔
204
                    case 'string':
1✔
205
                    case 'integer':
1✔
206
                        if (!empty($value)) {
1✔
207
                            $tags[] = substr($key, 0, 1) . $value;
1✔
208
                        }
209
                        break;
1✔
210
                }
211
            }
212
        }
213

214
        $tagsInline = implode('_', str_replace('_', '', $tags));
1✔
215
        $name = "{$asset['_path']}_{$asset['ext']}_$tagsInline";
1✔
216

217
        return $this->createKey($name, $asset['content'] ?? '');
1✔
218
    }
219

220
    /**
221
     * Creates key from a file: "RelativePathname__MD5".
222
     *
223
     * @throws RuntimeException
224
     */
225
    public function createKeyFromFile(\Symfony\Component\Finder\SplFileInfo $file): string
226
    {
227
        if (false === $content = Util\File::fileGetContents($file->getRealPath())) {
1✔
228
            throw new RuntimeException(\sprintf('Can\'t create cache key for "%s".', $file));
×
229
        }
230

231
        return $this->createKey($file->getRelativePathname(), $content);
1✔
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
    public function getContentFilePathname(string $path): string
270
    {
271
        $path = str_replace(['https://', 'http://'], '', $path); // remove protocol (if URL)
1✔
272

273
        return Util::joinFile($this->cacheDir, 'files', $path);
1✔
274
    }
275

276
    /**
277
     * Returns cache file pathname from key.
278
     */
279
    private function getFilePathname(string $key): string
280
    {
281
        return Util::joinFile($this->cacheDir, "$key.ser");
1✔
282
    }
283

284
    /**
285
     * Prepares and validate $key.
286
     */
287
    public static function sanitizeKey(string $key): string
288
    {
289
        $key = str_replace(['https://', 'http://'], '', $key); // remove protocol (if URL)
1✔
290
        $key = Page::slugify($key);                            // slugify
1✔
291
        $key = trim($key, '/');                                // remove leading/trailing slashes
1✔
292
        $key = str_replace(['\\', '/'], ['-', '-'], $key);     // replace slashes by hyphens
1✔
293
        $key = substr($key, 0, 200);                           // truncate to 200 characters (NTFS filename length limit is 255 characters)
1✔
294

295
        return $key;
1✔
296
    }
297

298
    /**
299
     * Removes previous cache files.
300
     */
301
    private function prune(string $key): bool
302
    {
303
        try {
304
            $keyAsArray = explode('__', self::sanitizeKey($key));
1✔
305
            // if 2 or more parts (with hash), remove all files with the same first part
306
            // pattern: `name__hash__version`
307
            if (!empty($keyAsArray[0]) && \count($keyAsArray) >= 2) {
1✔
308
                $pattern = Util::joinFile($this->cacheDir, $keyAsArray[0]) . '*';
1✔
309
                foreach (glob($pattern) ?: [] as $filename) {
1✔
310
                    Util\File::getFS()->remove($filename);
1✔
311
                }
312
            }
313
        } catch (\Exception $e) {
×
314
            $this->builder->getLogger()->error($e->getMessage());
×
315

316
            return false;
×
317
        }
318

319
        return true;
1✔
320
    }
321

322
    /**
323
     * Convert the various expressions of a TTL value into duration in seconds.
324
     */
325
    protected function duration(int|\DateInterval $ttl): int
326
    {
327
        if (\is_int($ttl)) {
1✔
328
            return $ttl;
1✔
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
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc