-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironment.php
More file actions
104 lines (89 loc) · 2.4 KB
/
Copy pathEnvironment.php
File metadata and controls
104 lines (89 loc) · 2.4 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/**
* Environment class file.
*
* @package Mantle
*/
namespace Mantle\Support;
use PhpOption\Option;
use Dotenv\Repository\RepositoryBuilder;
use Dotenv\Repository\RepositoryInterface;
use PhpOption\Some;
use function Mantle\Support\Helpers\value;
/**
* Storage of environment variables for the application.
*/
class Environment {
/**
* Variable repository.
*/
protected static ?RepositoryInterface $repository = null;
/**
* Get the environment repository instance.
*/
public static function get_repository(): RepositoryInterface {
if ( ! isset( static::$repository ) ) {
$builder = RepositoryBuilder::createWithDefaultAdapters();
static::$repository = $builder->immutable()->make();
}
return static::$repository;
}
/**
* Clear the environment repository instance.
*/
public static function clear(): void {
static::$repository = null;
}
/**
* Get the value of an environment variable.
*
* @param string $key Variable to retrieve.
* @param mixed $default Default value. Supports a closure callback.
*/
public static function get( string $key, mixed $default = null ): mixed {
$value = Option::fromValue( static::get_repository()->get( $key ) );
// Fallback to the VIP environment variable if the key is not found.
if ( $value instanceof \PhpOption\None ) {
$constant = strtoupper( $key );
$vip_constant = "VIP_ENV_VAR_{$key}";
if ( defined( $vip_constant ) ) {
$value = new Some( constant( $vip_constant ) );
} elseif ( defined( $constant ) ) {
$value = new Some( constant( $constant ) );
}
}
return $value
->map(
function ( $value ) {
switch ( strtolower( (string) $value ) ) {
case 'true':
case '(true)':
return true;
case 'false':
case '(false)':
return false;
case 'empty':
case '(empty)':
return '';
case 'null':
case '(null)':
return;
}
if ( preg_match( '/\A([\'"])(.*)\1\z/', (string) $value, $matches ) ) {
return $matches[2];
}
return $value;
}
)
->getOrCall( fn () => value( $default ) );
}
/**
* Get the value of an environment variable as a Mixed_Data object.
*
* @param string $key Variable to retrieve.
* @param mixed $default Default value. Supports a closure callback.
*/
public static function get_mixed( string $key, mixed $default = null ): Mixed_Data {
return Mixed_Data::of( static::get( $key, $default ) );
}
}