mirror of
https://github.com/zhamao-robot/zhamao-framework.git
synced 2026-07-21 23:55:35 +08:00
add environment variables support (#255)
This commit is contained in:
82
src/ZM/Config/Environment.php
Normal file
82
src/ZM/Config/Environment.php
Normal file
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace ZM\Config;
|
||||
|
||||
class Environment implements EnvironmentInterface
|
||||
{
|
||||
private const VALUE_MAP = [
|
||||
'true' => true,
|
||||
'(true)' => true,
|
||||
'false' => false,
|
||||
'(false)' => false,
|
||||
'null' => null,
|
||||
'(null)' => null,
|
||||
'empty' => '',
|
||||
];
|
||||
|
||||
private array $values;
|
||||
|
||||
/**
|
||||
* @param array $values 额外的环境变量,优先级高于系统环境变量
|
||||
* @param bool $overwrite 是否允许后续 set() 覆盖已有的环境变量
|
||||
*/
|
||||
public function __construct(
|
||||
array $values = [],
|
||||
private bool $overwrite = false
|
||||
) {
|
||||
$this->values = $values + $_ENV + $_SERVER;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function set(string $name, mixed $value): self
|
||||
{
|
||||
if (array_key_exists($name, $this->values) && !$this->overwrite) {
|
||||
// 如不允许覆盖已有的环境变量,则不做任何操作
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->values[$name] = $_ENV[$name] = $value;
|
||||
putenv("{$name}={$value}");
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function get(string $name, mixed $default = null): mixed
|
||||
{
|
||||
if (isset($this->values[$name])) {
|
||||
return $this->normalize($this->values[$name]);
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getAll(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($this->values as $key => $value) {
|
||||
$result[$key] = $this->normalize($value);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
protected function normalize(mixed $value): mixed
|
||||
{
|
||||
if (!is_string($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return self::VALUE_MAP[strtolower($value)] ?? $value;
|
||||
}
|
||||
}
|
||||
23
src/ZM/Config/EnvironmentInterface.php
Normal file
23
src/ZM/Config/EnvironmentInterface.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace ZM\Config;
|
||||
|
||||
interface EnvironmentInterface
|
||||
{
|
||||
/**
|
||||
* 设置环境变量
|
||||
*/
|
||||
public function set(string $name, mixed $value): self;
|
||||
|
||||
/**
|
||||
* 获取环境变量
|
||||
*/
|
||||
public function get(string $name, mixed $default = null): mixed;
|
||||
|
||||
/**
|
||||
* 获取所有环境变量
|
||||
*/
|
||||
public function getAll(): array;
|
||||
}
|
||||
Reference in New Issue
Block a user