|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace phpweb\Build; |
| 4 | + |
| 5 | +use RuntimeException; |
| 6 | +use stdClass; |
| 7 | +use function dirname; |
| 8 | +use function is_dir; |
| 9 | +use function is_readable; |
| 10 | + |
| 11 | +/** |
| 12 | + * Pregenerated Data Helper for storing and retrieving data from the compiled cache |
| 13 | + * |
| 14 | + * This utility is used by various build steps. |
| 15 | + * |
| 16 | + * At present these steps must be performed, and the cache committed to the GIT repository. |
| 17 | + * It is hoped that in the long-term this can be performed as part of CI/CD. |
| 18 | + */ |
| 19 | +final class VarCache |
| 20 | +{ |
| 21 | + private static function makePathForKey(string $key, bool $create = false): string |
| 22 | + { |
| 23 | + $path = __DIR__ . "/../../var/cache/{$key}.inc"; |
| 24 | + |
| 25 | + if ($create) { |
| 26 | + $basePath = dirname($path); |
| 27 | + is_dir($basePath) || mkdir($basePath, recursive:true); |
| 28 | + } |
| 29 | + |
| 30 | + return $path; |
| 31 | + } |
| 32 | + |
| 33 | + public static function ReadVar(string $key): mixed |
| 34 | + { |
| 35 | + static $dummy = null; |
| 36 | + $dummy ??= new stdClass(); |
| 37 | + $value = self::ReadVarWithDefault($key, $dummy); |
| 38 | + |
| 39 | + if ($value === $dummy) { |
| 40 | + throw new VarUnavailableException('Unable to read var cache value for ' . $key); |
| 41 | + } |
| 42 | + |
| 43 | + return $value; |
| 44 | + } |
| 45 | + |
| 46 | + public static function ReadVarWithDefault(string $key, mixed $default): mixed |
| 47 | + { |
| 48 | + $path = self::makePathForKey($key); |
| 49 | + if (is_readable($path)) { |
| 50 | + return require $path; |
| 51 | + } |
| 52 | + |
| 53 | + return $default; |
| 54 | + } |
| 55 | + |
| 56 | + public static function WriteVar(string $key, mixed $value): void |
| 57 | + { |
| 58 | + $path = self::makePathForKey($key, create: true); |
| 59 | + $result = file_put_contents( |
| 60 | + $path, |
| 61 | + "<?php\n\n/* this file is automatically generated. Do not edit. */\nreturn " . var_export($value, true) . ';', |
| 62 | + ); |
| 63 | + |
| 64 | + if ($result === false) { |
| 65 | + throw new RuntimeException('Unable to write var cache value for ' . $key); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments