Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
93.33% |
14 / 15 |
|
75.00% |
3 / 4 |
CRAP | |
0.00% |
0 / 1 |
| CacheBootstrap | |
93.33% |
14 / 15 |
|
75.00% |
3 / 4 |
10.03 | |
0.00% |
0 / 1 |
| resolveConfig | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
3 | |||
| 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 | |||
| 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') ?: ($fallbackCacheDir ?? sys_get_temp_dir()); |
| 23 | $ttl = (int) (getenv('SOURCE_CACHE_TTL') ?: 3600); |
| 24 | |
| 25 | return [$cacheDir, $ttl]; |
| 26 | } |
| 27 | |
| 28 | public static function create(string $cacheDir, int $ttl): CacheInterface |
| 29 | { |
| 30 | self::validateDirectory($cacheDir); |
| 31 | |
| 32 | $psr6 = new FilesystemAdapter(namespace: '', defaultLifetime: $ttl, directory: $cacheDir); |
| 33 | $cache = new Psr16Cache($psr6); |
| 34 | LoggerService::$cache = $cache; |
| 35 | |
| 36 | return $cache; |
| 37 | } |
| 38 | |
| 39 | public static function createFromEnv(?string $fallbackCacheDir = null): CacheInterface |
| 40 | { |
| 41 | [$cacheDir, $ttl] = self::resolveConfig($fallbackCacheDir); |
| 42 | |
| 43 | return self::create($cacheDir, $ttl); |
| 44 | } |
| 45 | |
| 46 | public static function validateDirectory(string $cacheDir): void |
| 47 | { |
| 48 | if (!is_dir($cacheDir)) { |
| 49 | if (!@mkdir($cacheDir, 0750, true) && !is_dir($cacheDir)) { |
| 50 | throw new \RuntimeException(sprintf('Cache directory "%s" could not be created', $cacheDir)); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | if (!is_writable($cacheDir)) { |
| 55 | throw new \RuntimeException(sprintf('Cache directory "%s" is not writable', $cacheDir)); |
| 56 | } |
| 57 | } |
| 58 | } |