v1.0.0.0
StocketBase
- <?php
-
- declare(strict_types=1);
-
- final class Config
- {
- private static ?array $values = null;
- private static ?string $envPath = null;
-
- public static function envFilePath(): string
- {
- if (self::$envPath !== null) {
- return self::$envPath;
- }
-
- $envRoot = dirname(__DIR__, 2) . '/stocketbase-env';
- $pointerFile = $envRoot . '/active-env.txt';
-
- if (is_file($pointerFile)) {
- $projectName = trim((string) file_get_contents($pointerFile));
- $candidate = $envRoot . '/.env.project.' . $projectName;
- if ($projectName !== '' && is_file($candidate)) {
- self::$envPath = $candidate;
- return self::$envPath;
- }
- }
-
- self::$envPath = $envRoot . '/.env';
- return self::$envPath;
- }
-
- public static function isInstalled(): bool
- {
- return is_file(self::envFilePath());
- }
-
- public static function load(): array
- {
- if (self::$values !== null) {
- return self::$values;
- }
-
- $path = self::envFilePath();
- $values = [];
-
- if (is_file($path)) {
- $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- foreach ($lines as $line) {
- $line = trim($line);
- if ($line === '' || str_starts_with($line, '#')) {
- continue;
- }
- if (!str_contains($line, '=')) {
- continue;
- }
- [$key, $value] = explode('=', $line, 2);
- $key = trim($key);
- $value = trim($value);
- if (strlen($value) >= 2 && $value[0] === '"' && $value[-1] === '"') {
- $value = substr($value, 1, -1);
- }
- $values[$key] = $value;
- }
- }
-
- self::$values = $values;
- return self::$values;
- }
-
- public static function get(string $key, ?string $default = null): ?string
- {
- $values = self::load();
- return $values[$key] ?? $default;
- }
-
- public static function write(string $projectName, array $values): bool
- {
- $envRoot = dirname(__DIR__, 2) . '/stocketbase-env';
-
- if (!is_dir($envRoot)) {
- if (!mkdir($envRoot, 0750, true) && !is_dir($envRoot)) {
- return false;
- }
- }
-
- $safeName = preg_replace('/[^a-zA-Z0-9_-]/', '', $projectName);
- if ($safeName === '') {
- $safeName = 'default';
- }
-
- $targetFile = $envRoot . '/.env.project.' . $safeName;
- $lines = [];
- foreach ($values as $key => $value) {
- $needsQuotes = str_contains((string) $value, ' ') || $value === '';
- $lines[] = $needsQuotes ? sprintf('%s="%s"', $key, $value) : sprintf('%s=%s', $key, $value);
- }
-
- $written = file_put_contents($targetFile, implode(PHP_EOL, $lines) . PHP_EOL);
- if ($written === false) {
- return false;
- }
-
- file_put_contents($envRoot . '/active-env.txt', $safeName);
- chmod($targetFile, 0640);
-
- self::$values = null;
- self::$envPath = null;
-
- return true;
- }
- }
-