95 lines
2.1 KiB
PHP
95 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Core;
|
|
|
|
class Config
|
|
{
|
|
private static ?self $instance = null;
|
|
|
|
/** @var array<string, mixed> */
|
|
private array $values = [];
|
|
|
|
private function __construct()
|
|
{
|
|
$this->loadEnv();
|
|
$this->loadConfigFiles();
|
|
}
|
|
|
|
public static function getInstance(): self
|
|
{
|
|
if (self::$instance === null) {
|
|
self::$instance = new self();
|
|
}
|
|
|
|
return self::$instance;
|
|
}
|
|
|
|
public function get(string $key, $default = null)
|
|
{
|
|
$segments = explode('.', $key);
|
|
$value = $this->values;
|
|
|
|
foreach ($segments as $segment) {
|
|
if (!is_array($value) || !array_key_exists($segment, $value)) {
|
|
return $default;
|
|
}
|
|
$value = $value[$segment];
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $config
|
|
*/
|
|
public function set(array $config): void
|
|
{
|
|
$this->values = array_replace_recursive($this->values, $config);
|
|
}
|
|
|
|
private function loadEnv(): void
|
|
{
|
|
$envPath = base_path('.env');
|
|
if (!file_exists($envPath)) {
|
|
return;
|
|
}
|
|
|
|
$lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
if ($lines === false) {
|
|
return;
|
|
}
|
|
|
|
foreach ($lines as $line) {
|
|
$trimmed = trim($line);
|
|
if ($trimmed === '' || $trimmed[0] === '#') {
|
|
continue;
|
|
}
|
|
|
|
[$name, $value] = array_map('trim', explode('=', $line, 2) + [1 => '']);
|
|
$value = trim($value, "\"' ");
|
|
$_ENV[$name] = $value;
|
|
putenv("{$name}={$value}");
|
|
}
|
|
}
|
|
|
|
private function loadConfigFiles(): void
|
|
{
|
|
$configDir = base_path('config');
|
|
if (!is_dir($configDir)) {
|
|
return;
|
|
}
|
|
|
|
$files = glob($configDir . '/*.php');
|
|
if ($files === false) {
|
|
return;
|
|
}
|
|
|
|
foreach ($files as $file) {
|
|
$key = basename($file, '.php');
|
|
/** @var array<string, mixed> $data */
|
|
$data = require $file;
|
|
$this->values[$key] = $data;
|
|
}
|
|
}
|
|
}
|