-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLazyFileConfig.php
More file actions
559 lines (450 loc) · 15.3 KB
/
Copy pathLazyFileConfig.php
File metadata and controls
559 lines (450 loc) · 15.3 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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<?php
declare(strict_types=1);
namespace Infocyph\ArrayKit\Config;
use Infocyph\ArrayKit\Array\DotNotation;
use Infocyph\ArrayKit\Config\Concerns\LazyFileConfigCacheTrait;
use InvalidArgumentException;
use RuntimeException;
use UnexpectedValueException;
class LazyFileConfig extends Config
{
use LazyFileConfigCacheTrait;
/**
* @var array<string, 'cache'|'missing'|'runtime'|'source'>
*/
protected array $loadedNamespaceOrigins = [];
/**
* @var array<string, bool>
*/
protected array $loadedNamespaces;
/**
* @param array<array-key, mixed> $items
*/
public function __construct(
protected string $directory,
protected string $extension = 'php',
array $items = [],
?string $namespaceCacheDirectory = null,
) {
$this->directory = rtrim($directory, DIRECTORY_SEPARATOR);
$this->extension = ltrim($extension, '.');
$this->items = $items;
$this->namespaceCacheDirectory = $namespaceCacheDirectory !== null
? rtrim($namespaceCacheDirectory, DIRECTORY_SEPARATOR)
: null;
$this->syncLoadedNamespacesFromItems();
}
#[\Override]
/**
* @return array<array-key, mixed>
*/
public function all(): array
{
throw new RuntimeException('LazyFileConfig does not support full config retrieval. At least one key is required.');
}
#[\Override]
/**
* @param string|array<array-key, mixed> $key
*/
public function fill(string|array $key, mixed $value = null): bool
{
$this->assertWritable();
$this->flushReadCache();
if (is_array($key)) {
foreach ($key as $path => $entry) {
if (!is_string($path)) {
throw new InvalidArgumentException('Fill keys must be dot-notation strings.');
}
$this->setPath($path, $entry, false);
}
} else {
$this->setPath($key, $value, false);
}
return true;
}
#[\Override]
/**
* @param string|int|array<int, string|int> $key
*/
public function forget(string|int|array $key): bool
{
$this->assertWritable();
$this->flushReadCache();
if (is_array($key)) {
foreach ($key as $path) {
$this->forgetPath((string) $path);
}
} else {
$this->forgetPath((string) $key);
}
return true;
}
#[\Override]
/**
* @param string|int|array<int, string|int>|null $key
*/
public function get(string|int|array|null $key = null, mixed $default = null): mixed
{
if ($key === null) {
throw new RuntimeException('At least one key is required for LazyFileConfig::get().');
}
if (is_int($key)) {
throw new InvalidArgumentException('Config key must be a dot-notation string.');
}
if (is_array($key)) {
if ($key === []) {
throw new RuntimeException('At least one key is required for LazyFileConfig::get().');
}
$results = [];
foreach ($key as $path) {
$results[(string) $path] = $this->getResolvedValue((string) $path, $default);
}
return $results;
}
return $this->getResolvedValue($key, $default);
}
#[\Override]
/**
* @param string|array<int, string> $keys
*/
public function has(string|array $keys): bool
{
$keys = (array) $keys;
if ($keys === []) {
return false;
}
return array_all($keys, fn($path) => $this->hasResolvedValue($path));
}
#[\Override]
/**
* @param string|array<int, string> $keys
*/
public function hasAny(string|array $keys): bool
{
$keys = (array) $keys;
if ($keys === []) {
return false;
}
return array_any($keys, fn($path) => $this->hasResolvedValue($path));
}
/**
* Returns true if the namespace has already been resolved (file found or missing).
*/
public function isLoaded(string $namespace): bool
{
return isset($this->loadedNamespaces[$this->normalizeNamespace($namespace)]);
}
#[\Override]
/**
* @param array<array-key, mixed> $resource
*/
public function loadArray(array $resource): bool
{
return $this->syncLoadedNamespacesAfter(parent::loadArray($resource));
}
/**
* Alias of isLoaded().
*/
public function loaded(string $namespace): bool
{
return $this->isLoaded($namespace);
}
/**
* @return string[] List of namespaces already resolved.
*/
public function loadedNamespaces(): array
{
return array_keys($this->loadedNamespaces);
}
#[\Override]
public function loadFile(string $path): bool
{
return $this->syncLoadedNamespacesAfter(parent::loadFile($path));
}
#[\Override]
/**
* @param array<array-key, mixed> $items
*/
public function merge(array $items): bool
{
$changed = parent::merge($items);
if ($changed) {
foreach (array_keys($items) as $namespace) {
if (is_string($namespace) && preg_match('/^[A-Za-z0-9_-]+$/', $namespace) === 1) {
$this->markNamespaceRuntime($namespace);
}
}
}
return $changed;
}
/**
* Preload one or multiple top-level config namespaces.
*
* @param string|array<int, string> $namespaces Namespace (e.g. "db") or list of namespaces.
*/
public function preload(string|array $namespaces): static
{
foreach ((array) $namespaces as $namespace) {
$this->loadNamespace($this->normalizeNamespace($namespace));
}
return $this;
}
#[\Override]
/**
* @param array<array-key, mixed>|string $source
*/
public function reload(array|string $source): bool
{
$this->assertWritable();
return $this->syncLoadedNamespacesAfter(parent::reload($source));
}
#[\Override]
/**
* @param array<array-key, mixed> $items
*/
public function replace(array $items): bool
{
$this->assertWritable();
return $this->syncLoadedNamespacesAfter(parent::replace($items));
}
#[\Override]
public function restore(string $name = 'default'): bool
{
return $this->syncLoadedNamespacesAfter(parent::restore($name));
}
#[\Override]
/**
* @param string|array<array-key, mixed>|null $key
*/
public function set(string|array|null $key = null, mixed $value = null, bool $overwrite = true): bool
{
$this->assertWritable();
$this->flushReadCache();
if ($key === null) {
throw new RuntimeException('At least one key is required for LazyFileConfig::set().');
}
if (is_array($key)) {
foreach ($key as $path => $entry) {
if (!is_string($path)) {
throw new InvalidArgumentException('Set keys must be dot-notation strings.');
}
$this->setPath($path, $entry, $overwrite);
}
} else {
$this->setPath($key, $value, $overwrite);
}
return true;
}
protected function forgetPath(string $path): void
{
[$namespace, $rest] = $this->splitPath($path);
$this->loadNamespace($namespace);
if (!array_key_exists($namespace, $this->items)) {
$this->markNamespaceRuntime($namespace);
return;
}
if ($rest === null || $rest === '') {
unset($this->items[$namespace]);
$this->markNamespaceRuntime($namespace);
return;
}
if (!is_array($this->items[$namespace])) {
return;
}
DotNotation::forget($this->items[$namespace], $rest);
$this->markNamespaceRuntime($namespace);
}
protected function getPath(string $path, mixed $default): mixed
{
[$namespace, $rest] = $this->splitPath($path);
$this->loadNamespace($namespace);
if (!array_key_exists($namespace, $this->items)) {
return $this->resolveDefault($default);
}
if ($rest === null || $rest === '') {
return $this->items[$namespace];
}
if (!is_array($this->items[$namespace])) {
return $this->resolveDefault($default);
}
return DotNotation::get($this->items[$namespace], $rest, $default);
}
protected function hasPath(string $path): bool
{
[$namespace, $rest] = $this->splitPath($path);
$this->loadNamespace($namespace);
if (!array_key_exists($namespace, $this->items)) {
return false;
}
if ($rest === null || $rest === '') {
return true;
}
if (!is_array($this->items[$namespace])) {
return false;
}
return DotNotation::has($this->items[$namespace], $rest);
}
protected function loadNamespace(string $namespace): void
{
if (isset($this->loadedNamespaces[$namespace])) {
return;
}
$cachedFile = $this->resolveCachedNamespaceFile($namespace);
$sourceFile = $this->resolveNamespaceFile($namespace);
$file = $cachedFile ?? $sourceFile;
if ($file === null) {
$this->loadedNamespaces[$namespace] = true;
$this->loadedNamespaceOrigins[$namespace] = 'missing';
return;
}
$loaded = include $file;
if (!is_array($loaded)) {
throw new UnexpectedValueException("Config file [{$file}] must return an array.");
}
$this->loadedNamespaces[$namespace] = true;
$this->loadedNamespaceOrigins[$namespace] = $cachedFile !== null ? 'cache' : 'source';
if (!array_key_exists($namespace, $this->items)) {
$this->items[$namespace] = $loaded;
$this->flushReadCache();
return;
}
if (is_array($this->items[$namespace])) {
$this->items[$namespace] = array_replace_recursive($loaded, $this->items[$namespace]);
$this->flushReadCache();
}
}
protected function normalizeNamespace(string $namespace): string
{
$trimmed = trim($namespace);
if ($trimmed === '' || !preg_match('/^[A-Za-z0-9_-]+$/', $trimmed)) {
throw new InvalidArgumentException("Invalid config namespace [{$namespace}].");
}
return $trimmed;
}
protected function resolveCachedNamespaceFile(string $namespace): ?string
{
$path = $this->cachedNamespacePath($namespace);
if ($path === null || !is_file($path) || !is_readable($path)) {
return null;
}
return $path;
}
protected function resolveLazyRawValue(string $path): mixed
{
[$namespace, $rest] = $this->splitPath($path);
if (array_key_exists($namespace, $this->items)) {
if ($rest === null || $rest === '') {
return $this->items[$namespace];
}
if (!is_array($this->items[$namespace])) {
return $this->missingValueMarker();
}
return DotNotation::get($this->items[$namespace], $rest, $this->missingValueMarker());
}
if ($this->isLoaded($namespace)) {
return $this->missingValueMarker();
}
if ($rest !== null && $this->isEligibleFlatLookupPath($path)) {
$flatValue = $this->flatLeafValue($path);
if ($flatValue !== $this->missingValueMarker()) {
return $flatValue;
}
}
$this->loadNamespace($namespace);
if (!array_key_exists($namespace, $this->items)) {
return $this->missingValueMarker();
}
if ($rest === null || $rest === '') {
return $this->items[$namespace];
}
if (!is_array($this->items[$namespace])) {
return $this->missingValueMarker();
}
return DotNotation::get($this->items[$namespace], $rest, $this->missingValueMarker());
}
protected function resolveNamespaceFile(string $namespace): ?string
{
$file = $this->directory . DIRECTORY_SEPARATOR . $namespace . '.' . $this->extension;
if (!is_file($file) || !is_readable($file)) {
return null;
}
return $file;
}
#[\Override]
protected function resolveRawValue(int|string $key): mixed
{
if (!is_string($key)) {
return parent::resolveRawValue($key);
}
if (!$this->readCacheEnabled() || !$this->isReadCacheSafePath($key)) {
return $this->resolveLazyRawValue($key);
}
$cacheKey = $this->valueCacheKey($key);
if (array_key_exists($cacheKey, $this->resolvedValueCache)) {
return $this->resolvedValueCache[$cacheKey];
}
return $this->cacheResolvedValue($cacheKey, $this->resolveLazyRawValue($key));
}
protected function setPath(string $path, mixed $value, bool $overwrite): void
{
[$namespace, $rest] = $this->splitPath($path);
$this->loadNamespace($namespace);
if ($rest === null || $rest === '') {
if ($overwrite || !array_key_exists($namespace, $this->items)) {
$this->items[$namespace] = $value;
$this->markNamespaceRuntime($namespace);
}
return;
}
$namespaceConfig = $this->items[$namespace] ?? [];
if (!is_array($namespaceConfig)) {
$namespaceConfig = [];
}
DotNotation::set($namespaceConfig, $rest, $value, $overwrite);
$this->items[$namespace] = $namespaceConfig;
$this->markNamespaceRuntime($namespace);
}
/**
* @return array{0: string, 1: string|null}
*/
protected function splitPath(string $path): array
{
$trimmed = trim($path);
if ($trimmed === '') {
throw new InvalidArgumentException('Config key must not be empty.');
}
$dotPosition = strpos($trimmed, '.');
if ($dotPosition === false) {
$namespace = $this->normalizeNamespace($trimmed);
return [$namespace, null];
}
$namespace = $this->normalizeNamespace(substr($trimmed, 0, $dotPosition));
$rest = substr($trimmed, $dotPosition + 1);
return [$namespace, $rest === '' ? null : $rest];
}
protected function syncLoadedNamespacesFromItems(): void
{
parent::flushReadCache();
$this->loadedNamespaces = [];
$this->loadedNamespaceOrigins = [];
foreach ($this->items as $namespace => $_) {
if (!is_string($namespace) || !preg_match('/^[A-Za-z0-9_-]+$/', $namespace)) {
continue;
}
$this->loadedNamespaces[$namespace] = true;
$this->loadedNamespaceOrigins[$namespace] = 'runtime';
}
}
private function markNamespaceRuntime(string $namespace): void
{
$this->loadedNamespaces[$namespace] = true;
$this->loadedNamespaceOrigins[$namespace] = 'runtime';
}
private function syncLoadedNamespacesAfter(bool $changed): bool
{
if ($changed) {
$this->syncLoadedNamespacesFromItems();
}
return $changed;
}
}