-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironmentVariable.php
More file actions
62 lines (49 loc) · 1.92 KB
/
EnvironmentVariable.php
File metadata and controls
62 lines (49 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace TinyBlocks\EnvironmentVariable;
use TinyBlocks\EnvironmentVariable\Internal\Exceptions\EnvironmentVariableMissing;
use TinyBlocks\EnvironmentVariable\Internal\Exceptions\InvalidEnvironmentValue;
final readonly class EnvironmentVariable implements Environment
{
private function __construct(private string $value, private string $variable)
{
}
public static function from(string $name): EnvironmentVariable
{
$environmentVariable = getenv($name);
return $environmentVariable === false
? throw new EnvironmentVariableMissing(variable: $name)
: new EnvironmentVariable(value: $environmentVariable, variable: $name);
}
public static function fromOrDefault(string $name, ?string $defaultValueIfNotFound = null): EnvironmentVariable
{
$environmentVariable = getenv($name);
return $environmentVariable === false
? new EnvironmentVariable(value: (string)$defaultValueIfNotFound, variable: $name)
: new EnvironmentVariable(value: $environmentVariable, variable: $name);
}
public function hasValue(): bool
{
return match (strtolower(trim($this->value))) {
'', 'null' => false,
default => true
};
}
public function toString(): string
{
return $this->value;
}
public function toInteger(): int
{
return is_numeric($this->value)
? (int)$this->value
: throw InvalidEnvironmentValue::fromIntegerConversion(value: $this->value, variable: $this->variable);
}
public function toBoolean(): bool
{
$filteredValue = filter_var($this->value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
return $filteredValue !== null
? $filteredValue
: throw InvalidEnvironmentValue::fromBooleanConversion(value: $this->value, variable: $this->variable);
}
}