1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Karma\Configuration; |
6
|
|
|
|
7
|
|
|
use Karma\Configuration; |
8
|
|
|
|
9
|
|
|
abstract class AbstractReader implements Configuration |
10
|
|
|
{ |
11
|
|
|
private array |
|
|
|
|
12
|
|
|
$overridenVariables, |
13
|
|
|
$customData; |
14
|
|
|
|
15
|
|
|
protected string |
16
|
|
|
$defaultEnvironment; |
17
|
|
|
|
18
|
278 |
|
public function __construct() |
19
|
|
|
{ |
20
|
278 |
|
$this->defaultEnvironment = 'dev'; |
21
|
278 |
|
$this->overridenVariables = []; |
22
|
278 |
|
$this->customData = []; |
23
|
278 |
|
} |
24
|
|
|
|
25
|
231 |
|
public function read(string $variable, ?string $environment = null) |
26
|
|
|
{ |
27
|
231 |
|
$value = null; |
28
|
|
|
|
29
|
231 |
|
if(array_key_exists($variable, $this->overridenVariables)) |
30
|
|
|
{ |
31
|
6 |
|
$value = $this->overridenVariables[$variable]; |
32
|
|
|
} |
33
|
|
|
else |
34
|
|
|
{ |
35
|
229 |
|
$value = $this->readRaw($variable, $environment); |
36
|
|
|
} |
37
|
|
|
|
38
|
223 |
|
return $this->handleCustomData($value); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
abstract protected function readRaw(string $variable, ?string $environment = null); |
42
|
|
|
|
43
|
68 |
|
public function setDefaultEnvironment(string $environment): void |
44
|
|
|
{ |
45
|
68 |
|
if(! empty($environment) && is_string($environment)) |
46
|
|
|
{ |
47
|
68 |
|
$this->defaultEnvironment = $environment; |
48
|
|
|
} |
49
|
68 |
|
} |
50
|
|
|
|
51
|
12 |
|
public function getAllValuesForEnvironment(?string $environment = null): array |
52
|
|
|
{ |
53
|
12 |
|
$result = []; |
54
|
|
|
|
55
|
12 |
|
$variables = $this->getAllVariables(); |
56
|
|
|
|
57
|
12 |
|
foreach($variables as $variable) |
58
|
|
|
{ |
59
|
|
|
try |
60
|
|
|
{ |
61
|
12 |
|
$value = $this->read($variable, $environment); |
62
|
|
|
} |
63
|
7 |
|
catch(\RuntimeException $e) |
64
|
|
|
{ |
65
|
7 |
|
$value = Configuration::NOT_FOUND; |
66
|
|
|
} |
67
|
|
|
|
68
|
12 |
|
$result[$variable] = $value; |
69
|
|
|
} |
70
|
|
|
|
71
|
12 |
|
return $result; |
72
|
|
|
} |
73
|
|
|
|
74
|
8 |
|
public function overrideVariable(string $variable, $value): void |
75
|
|
|
{ |
76
|
8 |
|
$this->overridenVariables[$variable] = $value; |
77
|
8 |
|
} |
78
|
|
|
|
79
|
5 |
|
public function setCustomData(string $customDataName, $value): void |
80
|
|
|
{ |
81
|
5 |
|
$key = '${' . $customDataName . '}'; |
82
|
5 |
|
$this->customData[$key] = $value; |
83
|
5 |
|
} |
84
|
|
|
|
85
|
223 |
|
private function handleCustomData($value) |
86
|
|
|
{ |
87
|
223 |
|
if(is_array($value)) |
88
|
|
|
{ |
89
|
57 |
|
return array_map(function($value) { |
90
|
48 |
|
return $this->handleCustomData($value); |
91
|
57 |
|
}, $value); |
92
|
|
|
} |
93
|
|
|
|
94
|
214 |
|
if(! is_string($value)) |
95
|
|
|
{ |
96
|
98 |
|
return $value; |
97
|
|
|
} |
98
|
|
|
|
99
|
145 |
|
return strtr($value, $this->customData); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|