Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
Cache
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
4 / 4
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 forget
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 cacheFilePath
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Helpers;
6
7class Cache
8{
9    public function __construct(protected string $path)
10    {
11    }
12
13    /**
14     * Returns the value cached for $key, $default if not
15     *
16     * If $default is a callable it calls it for the value to be cached
17     *
18     */
19    public function get(string $key, mixed $default = null, int $seconds = 60 * 60): mixed
20    {
21        $cacheFile = $this->cacheFilePath($key);
22
23        // Check for file existence, forget old ones
24        $exists = file_exists($cacheFile);
25        if ($exists && filemtime($cacheFile) < time() - $seconds) {
26            $this->forget($key);
27            $exists = false;
28        }
29
30        // Handle callback to get default value
31        if (!$exists) {
32            if (!is_callable($default)) {
33                return $default;
34            }
35
36            file_put_contents($cacheFile, serialize($default()));
37        }
38
39        // Get data from cache
40        return unserialize(file_get_contents($cacheFile));
41    }
42
43    public function forget(string $key): void
44    {
45        $cacheFile = $this->cacheFilePath($key);
46        if (!file_exists($cacheFile)) {
47            return;
48        }
49
50        unlink($cacheFile);
51    }
52
53    protected function cacheFilePath(string $key): string
54    {
55        return $this->path . '/' . $key . '.cache';
56    }
57}