1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Antidot\Yaml; |
6
|
|
|
|
7
|
|
|
use Laminas\Config\Reader\Yaml; |
8
|
|
|
use Laminas\ConfigAggregator\GlobTrait; |
9
|
|
|
use RuntimeException; |
10
|
|
|
use Symfony\Component\Yaml\Yaml as YamlParser; |
11
|
|
|
|
12
|
|
|
class YamlConfigProvider |
13
|
|
|
{ |
14
|
|
|
use GlobTrait; |
15
|
|
|
|
16
|
|
|
private string $pattern; |
17
|
|
|
|
18
|
|
|
public function __construct(string $pattern) |
19
|
|
|
{ |
20
|
|
|
$this->pattern = $pattern; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Provide configuration. |
25
|
|
|
* |
26
|
|
|
* Globs the given files, and passes the result to ConfigFactory::fromFiles |
27
|
|
|
* for purposes of returning merged configuration. |
28
|
|
|
* |
29
|
|
|
* @return array<mixed> |
30
|
|
|
*/ |
31
|
|
|
public function __invoke(): array |
32
|
|
|
{ |
33
|
|
|
$files = $this->glob($this->pattern); |
34
|
|
|
|
35
|
|
|
return $this->fromFiles($files); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param array<mixed> $files |
40
|
|
|
* @return array<mixed> |
41
|
|
|
*/ |
42
|
|
|
private function fromFiles(array $files): array |
43
|
|
|
{ |
44
|
|
|
$config = [[]]; |
45
|
|
|
foreach ($files as $file) { |
46
|
|
|
$config[] = $this->fromFile($file); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return array_replace_recursive(...$config) ?? []; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @return array<mixed> |
54
|
|
|
*/ |
55
|
|
|
private function fromFile(string $filename): array |
56
|
|
|
{ |
57
|
|
|
$filepath = $filename; |
58
|
|
|
if (!file_exists($filename)) { |
59
|
|
|
throw new RuntimeException(sprintf( |
60
|
|
|
'Filename "%s" cannot be found relative to the working directory', |
61
|
|
|
$filename |
62
|
|
|
)); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$pathinfo = pathinfo($filepath); |
66
|
|
|
|
67
|
|
|
if (!isset($pathinfo['extension'])) { |
68
|
|
|
throw new RuntimeException(sprintf( |
69
|
|
|
'Filename "%s" is missing an extension and cannot be auto-detected', |
70
|
|
|
$filename |
71
|
|
|
)); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$extension = strtolower($pathinfo['extension']); |
75
|
|
|
|
76
|
|
|
if (false === in_array($extension, ['yaml', 'yml'])) { |
77
|
|
|
throw new RuntimeException(sprintf( |
78
|
|
|
"File '%s' doesn't exist or not readable", |
79
|
|
|
$filename |
80
|
|
|
)); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$reader = new Yaml(static function ($config) { |
84
|
|
|
return YamlParser::parse($config); |
85
|
|
|
}); |
86
|
|
|
|
87
|
|
|
return $reader->fromFile($filepath); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|