Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
90.48% |
19 / 21 |
|
60.00% |
3 / 5 |
CRAP | |
0.00% |
0 / 1 |
| CacheBootstrap | |
90.48% |
19 / 21 |
|
60.00% |
3 / 5 |
15.19 | |
0.00% |
0 / 1 |
| resolveConfig | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 | |||
| create | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| createFromEnv | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| validateDirectory | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
5.20 | |||
| getenvInt | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
4.25 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace BO\Slim\Helper; |
| 6 | |
| 7 | use BO\Slim\LoggerService; |
| 8 | use Psr\SimpleCache\CacheInterface; |
| 9 | use Symfony\Component\Cache\Adapter\FilesystemAdapter; |
| 10 | use Symfony\Component\Cache\Psr16Cache; |
| 11 | |
| 12 | /** |
| 13 | * Shared filesystem cache bootstrap for module Application classes. |
| 14 | */ |
| 15 | final class CacheBootstrap |
| 16 | { |
| 17 | /** |
| 18 | * @return array{0: string, 1: int} |
| 19 | */ |
| 20 | public static function resolveConfig(?string $fallbackCacheDir = null): array |
| 21 | { |
| 22 | $cacheDir = getenv('CACHE_DIR'); |
| 23 | if ($cacheDir === false || $cacheDir === '' || $cacheDir === '0') { |
| 24 | $cacheDir = $fallbackCacheDir ?? sys_get_temp_dir(); |
| 25 | } |
| 26 | $ttl = self::getenvInt('SOURCE_CACHE_TTL', 3600); |
| 27 | |
| 28 | return [$cacheDir, $ttl]; |
| 29 | } |
| 30 | |
| 31 | public static function create(string $cacheDir, int $ttl): CacheInterface |
| 32 | { |
| 33 | self::validateDirectory($cacheDir); |
| 34 | |
| 35 | $psr6 = new FilesystemAdapter(namespace: '', defaultLifetime: $ttl, directory: $cacheDir); |
| 36 | $cache = new Psr16Cache($psr6); |
| 37 | LoggerService::$cache = $cache; |
| 38 | |
| 39 | return $cache; |
| 40 | } |
| 41 | |
| 42 | public static function createFromEnv(?string $fallbackCacheDir = null): CacheInterface |
| 43 | { |
| 44 | [$cacheDir, $ttl] = self::resolveConfig($fallbackCacheDir); |
| 45 | |
| 46 | return self::create($cacheDir, $ttl); |
| 47 | } |
| 48 | |
| 49 | public static function validateDirectory(string $cacheDir): void |
| 50 | { |
| 51 | if (!is_dir($cacheDir)) { |
| 52 | if (!@mkdir($cacheDir, 0750, true) && !is_dir($cacheDir)) { |
| 53 | throw new \RuntimeException(sprintf('Cache directory "%s" could not be created', $cacheDir)); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | if (!is_writable($cacheDir)) { |
| 58 | throw new \RuntimeException(sprintf('Cache directory "%s" is not writable', $cacheDir)); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | private static function getenvInt(string $name, int $default): int |
| 63 | { |
| 64 | $value = getenv($name); |
| 65 | if ($value === false || $value === '' || $value === '0') { |
| 66 | return $default; |
| 67 | } |
| 68 | |
| 69 | return (int) $value; |
| 70 | } |
| 71 | } |