Lines
90.47%
19 / 21
Methods
60.00%
3 / 5
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| 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 | ||
| 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 | } |