-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironmentConfig.php
More file actions
188 lines (152 loc) · 7.07 KB
/
Copy pathEnvironmentConfig.php
File metadata and controls
188 lines (152 loc) · 7.07 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
<?php
declare(strict_types=1);
namespace MagicPush\CliToolkit\Parametizer;
use Exception;
use MagicPush\CliToolkit\Utils;
use RuntimeException;
use TypeError;
class EnvironmentConfig {
public const string CONFIG_FILENAME = 'parametizer.env.json';
/* AVAILABLE PROPERTIES -> */
public int $listPaddingLeftMain = 1;
public int $listPaddingLeftCommand = 2;
public int $listPaddingLeftCommandDescription = 4;
public int $helpGeneratorPaddingLeftMain = 2;
public int $helpGeneratorPaddingLeftParameterDescription = 4;
public int $helpGeneratorShortDescriptionCharsMinBeforeFullStop = 40;
public int $helpGeneratorShortDescriptionCharsMax = 70;
public int $helpGeneratorUsageNonRequiredOptionsMax = 5;
public ?string $optionHelpShortName = null;
/* <- AVAILABLE PROPERTIES */
/** @var bool[] (string) property name => (values do not matter) */
protected array $propertiesNotYetInitializedFromFiles;
public function __construct() {
// Initialize the list or properties settable from config files:
$this->propertiesNotYetInitializedFromFiles = array_fill_keys(
array_keys(get_object_vars(...)->__invoke($this)),
true,
);
}
public function toJsonFileContent(): string {
return json_encode(
$this,
JSON_THROW_ON_ERROR
| JSON_UNESCAPED_UNICODE
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_LINE_TERMINATORS
| JSON_PRETTY_PRINT,
) . PHP_EOL;
}
protected function haveFilesInitializedAllProperties(): bool {
return empty($this->propertiesNotYetInitializedFromFiles);
}
/**
* Fills the instance properties with a JSON config file contents.
*
* Affects only the properties mentioned in a file, the rest are kept unchanged.
*/
public function fillFromJsonConfigFile(string $jsonConfigPath, bool $throwOnException = false): void {
$configAbsolutePath = realpath($jsonConfigPath);
if (false === $configAbsolutePath || !is_readable($configAbsolutePath)) {
if (!$throwOnException) {
return;
}
throw new RuntimeException('Invalid path or the file does not exist: ' . var_export($jsonConfigPath, true));
}
try {
$parsedConfig = json_decode(file_get_contents($configAbsolutePath), true, flags: JSON_THROW_ON_ERROR);
} catch (Exception $e) {
if (!$throwOnException) {
return;
}
throw new RuntimeException(
"Unable to read the environment config '{$configAbsolutePath}': {$e->getMessage()}",
);
}
foreach ($this->propertiesNotYetInitializedFromFiles as $propertyName => $notUsed) {
if (array_key_exists($propertyName, $parsedConfig)) {
try {
$this->$propertyName = $parsedConfig[$propertyName];
} catch (Exception|TypeError $e) {
if (!$throwOnException) {
continue;
}
throw new RuntimeException(
"Unable to set '{$propertyName}' environment config setting to the value: "
. var_export($parsedConfig[$propertyName], true)
. "; source file '{$configAbsolutePath}'; error: {$e->getMessage()}",
);
}
unset($this->propertiesNotYetInitializedFromFiles[$propertyName]);
}
}
}
/**
* Creates an {@see EnvironmentConfig} instance with default values and tries to fill it from config files
* {@see CONFIG_FILENAME} found along the way from `$bottommostDirectoryPath` to `$topmostDirectoryPath`.
*
* @param string $bottommostDirectoryPath Should be filled with a readable path to a directory
* where a script config might be located.
* @param string|null $topmostDirectoryPath The method will not search config files above this directory.
* If `null`, will try to detect a path via
* {@see Utils::detectTopmostProjectRootDirectory()}.
*/
public static function createFromConfigsBottomUpHierarchy(
?string $bottommostDirectoryPath = null,
?string $topmostDirectoryPath = null,
bool $throwOnException = false,
): static {
$envConfig = new EnvironmentConfig();
if (null === $bottommostDirectoryPath) {
$bottommostDirectoryPath = static::detectBottommostDirectoryPath();
}
$bottommostDirectoryPathValidated = null !== $bottommostDirectoryPath
? realpath($bottommostDirectoryPath)
: false;
if (false === $bottommostDirectoryPathValidated || !is_readable($bottommostDirectoryPathValidated)) {
if (!$throwOnException) {
return $envConfig;
}
throw new RuntimeException(
'Unable to read the bottommost directory: ' . var_export($bottommostDirectoryPath, true),
);
}
if (null === $topmostDirectoryPath) {
$topmostDirectoryPath = Utils::detectTopmostProjectRootDirectory();
}
$topmostDirectoryPathValidated = realpath($topmostDirectoryPath);
if (false === $topmostDirectoryPathValidated || !is_readable($topmostDirectoryPathValidated)) {
if (!$throwOnException) {
return $envConfig;
}
throw new RuntimeException(
'Unable to read the topmost directory: ' . var_export($topmostDirectoryPath, true),
);
}
$currentDirPath = $bottommostDirectoryPathValidated;
while (true) {
$configPath = $currentDirPath . '/' . static::CONFIG_FILENAME;
if (file_exists($configPath)) {
$envConfig->fillFromJsonConfigFile($configPath, $throwOnException);
// Values from "closer" config files are prioritized over "farther" config files.
// Thus, if all properties are initialized from already detected files, we should stop the search.
if ($envConfig->haveFilesInitializedAllProperties()) {
return $envConfig;
}
}
if ($currentDirPath === $topmostDirectoryPath) {
return $envConfig;
}
$previousDirPath = $currentDirPath;
$currentDirPath = dirname($currentDirPath);
// Prevents a possible endless loop, if `$topmostDirectoryPath` is unreachable:
if ($currentDirPath === $previousDirPath) {
return $envConfig;
}
}
}
protected static function detectBottommostDirectoryPath(): ?string {
$debugBacktrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
return $debugBacktrace[array_key_last($debugBacktrace)]['file'] ?? null;
}
}