This repository was archived by the owner on Jan 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathConfigAggregator.php
340 lines (299 loc) · 9.44 KB
/
ConfigAggregator.php
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
/**
* @see https://github.com/zendframework/zend-config-aggregator for the canonical source repository
* @copyright Copyright (c) 2016 Zend Technologies USA Inc. (http://www.zend.com)
* @copyright Copyright (c) 2015-2016 Mateusz Tymek (http://mateusztymek.pl)
* @license https://github.com/zendframework/zend-config-aggregator/blob/master/LICENSE.md New BSD License
*/
namespace Zend\ConfigAggregator;
use Closure;
use Generator;
use Zend\Stdlib\ArrayUtils\MergeRemoveKey;
use Zend\Stdlib\ArrayUtils\MergeReplaceKeyInterface;
use function array_key_exists;
use function chmod;
use function class_exists;
use function date;
use function fclose;
use function file_exists;
use function flock;
use function fopen;
use function fputs;
use function ftruncate;
use function get_class;
use function gettype;
use function is_array;
use function is_callable;
use function is_int;
use function is_object;
use function is_string;
use function sprintf;
use function var_export;
/**
* Aggregate configuration generated by configuration providers.
*/
class ConfigAggregator
{
const ENABLE_CACHE = 'config_cache_enabled';
const CACHE_FILEMODE = 'config_cache_filemode';
const CACHE_TEMPLATE = <<< 'EOT'
<?php
/**
* This configuration cache file was generated by %s
* at %s
*/
return %s;
EOT;
/**
* @var array
*/
private $config;
/**
* @param array $providers Array of providers. These may be callables, or
* string values representing classes that act as providers. If the
* latter, they must be instantiable without constructor arguments.
* @param null|string $cachedConfigFile Configuration cache file; config is
* loaded from this file if present, and written to it if not. null
* disables caching.
* @param array $postProcessors Array of processors. These may be callables, or
* string values representing classes that act as processors. If the
* latter, they must be instantiable without constructor arguments.
*/
public function __construct(
array $providers = [],
$cachedConfigFile = null,
array $postProcessors = []
) {
if ($this->loadConfigFromCache($cachedConfigFile)) {
return;
}
$this->config = $this->loadConfigFromProviders($providers);
$this->config = $this->postProcessConfig($postProcessors, $this->config);
$this->cacheConfig($this->config, $cachedConfigFile);
}
/**
* @return array
*/
public function getMergedConfig()
{
return $this->config;
}
/**
* Resolve a provider.
*
* If the provider is a string class name, instantiates that class and
* tests if it is callable, returning it if true.
*
* If the provider is a callable, returns it verbatim.
*
* Raises an exception for any other condition.
*
* @param string|callable $provider
* @return callable
* @throws InvalidConfigProviderException
*/
private function resolveProvider($provider)
{
if (is_string($provider)) {
if (! class_exists($provider)) {
throw InvalidConfigProviderException::fromNamedProvider($provider);
}
$provider = new $provider();
}
if (! is_callable($provider)) {
$type = $this->detectVariableType($provider);
throw InvalidConfigProviderException::fromUnsupportedType($type);
}
return $provider;
}
/**
* Resolve a processor.
*
* If the processor is a string class name, instantiates that class and
* tests if it is callable, returning it if true.
*
* If the processor is a callable, returns it verbatim.
*
* Raises an exception for any other condition.
*
* @param string|callable $processor
* @return callable
* @throws InvalidConfigProcessorException
*/
private function resolveProcessor($processor)
{
if (is_string($processor)) {
if (! class_exists($processor)) {
throw InvalidConfigProcessorException::fromNamedProcessor($processor);
}
$processor = new $processor();
}
if (! is_callable($processor)) {
$type = $this->detectVariableType($processor);
throw InvalidConfigProcessorException::fromUnsupportedType($type);
}
return $processor;
}
/**
* Perform a recursive merge of two multi-dimensional arrays.
*
* Copied from https://github.com/zendframework/zend-stdlib/blob/980ce463c29c1a66c33e0eb67961bba895d0e19e/src/ArrayUtils.php#L269
*
* @param array $a
* @param array $b
* @return $a
*/
private function mergeArray(array $a, array $b)
{
foreach ($b as $key => $value) {
if ($value instanceof MergeReplaceKeyInterface) {
$a[$key] = $value->getData();
} elseif (isset($a[$key]) || array_key_exists($key, $a)) {
if ($value instanceof MergeRemoveKey) {
unset($a[$key]);
} elseif (is_int($key)) {
$a[] = $value;
} elseif (is_array($value) && is_array($a[$key])) {
$a[$key] = $this->mergeArray($a[$key], $value);
} else {
$a[$key] = $value;
}
} else {
if (! $value instanceof MergeRemoveKey) {
$a[$key] = $value;
}
}
}
return $a;
}
/**
* Merge configuration from a provider with existing configuration.
*
* @param array $mergedConfig Passed by reference as a performance/resource
* optimization.
* @param mixed|array $config Configuration generated by the $provider.
* @param callable $provider Provider responsible for generating $config;
* used for exception messages only.
* @return void
* @throws InvalidConfigProviderException
*/
private function mergeConfig(&$mergedConfig, $config, callable $provider)
{
if (! is_array($config)) {
$type = $this->detectVariableType($provider);
throw new InvalidConfigProviderException(sprintf(
'Cannot read config from %s; does not return array',
$type
));
}
$mergedConfig = $this->mergeArray($mergedConfig, $config);
}
/**
* Iterate providers, merging config from each with the previous.
*
* @param array $providers
* @return array
*/
private function loadConfigFromProviders(array $providers)
{
$mergedConfig = [];
foreach ($providers as $provider) {
$provider = $this->resolveProvider($provider);
$config = $provider();
if (! $config instanceof Generator) {
$this->mergeConfig($mergedConfig, $config, $provider);
continue;
}
// Handle generators
foreach ($config as $cfg) {
$this->mergeConfig($mergedConfig, $cfg, $provider);
}
}
return $mergedConfig;
}
/**
* Attempt to load the configuration from a cache file.
*
* @param null|string $cachedConfigFile
* @return bool
*/
private function loadConfigFromCache($cachedConfigFile)
{
if (null === $cachedConfigFile) {
return false;
}
if (! file_exists($cachedConfigFile)) {
return false;
}
$this->config = require $cachedConfigFile;
return true;
}
/**
* Attempt to cache discovered configuration.
*
* @param array $config
* @param null|string $cachedConfigFile
* @param int $mode
*/
private function cacheConfig(array $config, $cachedConfigFile)
{
if (null === $cachedConfigFile) {
return;
}
if (empty($config[static::ENABLE_CACHE])) {
return;
}
$mode = isset($config[self::CACHE_FILEMODE]) ? $config[self::CACHE_FILEMODE] : null;
$tempFile = sys_get_temp_dir() . '/' . basename($cachedConfigFile) . '.tmp';
$fh = fopen($tempFile, 'c');
if (! $fh) {
return;
}
if (! flock($fh, LOCK_EX | LOCK_NB)) {
fclose($fh);
return;
}
if ($mode !== null) {
chmod($tempFile, $mode);
}
ftruncate($fh, 0);
fputs($fh, sprintf(
self::CACHE_TEMPLATE,
get_class($this),
date('c'),
var_export($config, true)
));
rename($tempFile, $cachedConfigFile);
flock($fh, LOCK_UN);
fclose($fh);
}
/**
* @return array
*/
private function postProcessConfig(array $processors, array $config)
{
foreach ($processors as $processor) {
$processor = $this->resolveProcessor($processor);
$config = $processor($config);
}
return $config;
}
/**
* @param Closure|object|callable $variable
*
* @return string
*/
private function detectVariableType($variable)
{
if ($variable instanceof Closure) {
return 'Closure';
}
if (is_object($variable)) {
return get_class($variable);
}
if (is_callable($variable)) {
return is_string($variable) ? $variable : gettype($variable);
}
return gettype($variable);
}
}