|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the daikon-cqrs/config project. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Daikon\Config; |
|
10
|
|
|
|
|
11
|
|
|
use Symfony\Component\Finder\Finder; |
|
12
|
|
|
use Symfony\Component\Yaml\Yaml; |
|
13
|
|
|
|
|
14
|
|
|
final class YamlConfigLoader implements ConfigLoaderInterface |
|
15
|
|
|
{ |
|
16
|
|
|
private Yaml $yamlParser; |
|
17
|
|
|
|
|
18
|
|
|
private Finder $finder; |
|
19
|
|
|
|
|
20
|
2 |
|
public function __construct(Yaml $yamlParser = null, Finder $finder = null) |
|
21
|
|
|
{ |
|
22
|
2 |
|
$this->yamlParser = $yamlParser ?? new Yaml; |
|
23
|
2 |
|
$this->finder = $finder ?? new Finder; |
|
24
|
2 |
|
} |
|
25
|
|
|
|
|
26
|
2 |
|
public function load(array $locations, array $sources): array |
|
27
|
|
|
{ |
|
28
|
2 |
|
return array_reduce( |
|
29
|
2 |
|
$locations, |
|
30
|
|
|
/** @param string|string[] $location */ |
|
31
|
2 |
|
function (array $config, $location) use ($sources): array { |
|
32
|
2 |
|
return array_replace_recursive($config, $this->loadSources($location, $sources)); |
|
33
|
2 |
|
}, |
|
34
|
2 |
|
[] |
|
35
|
|
|
); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** @param string|string[] $location */ |
|
39
|
2 |
|
private function loadSources($location, array $sources): array |
|
40
|
|
|
{ |
|
41
|
2 |
|
$location = array_filter((array)$location, 'is_dir'); |
|
42
|
|
|
|
|
43
|
2 |
|
if (empty($location) || empty($sources)) { |
|
44
|
|
|
return []; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
return array_reduce($sources, function (array $config, string $source) use ($location): array { |
|
48
|
2 |
|
foreach ($this->finder |
|
49
|
2 |
|
->create() |
|
50
|
2 |
|
->files() |
|
51
|
2 |
|
->ignoreUnreadableDirs() |
|
52
|
2 |
|
->in($location) |
|
53
|
2 |
|
->name($source) |
|
54
|
2 |
|
->sortByName() as $file) { |
|
55
|
2 |
|
if ($file->isReadable()) { |
|
56
|
2 |
|
$config = array_replace_recursive($config, $this->yamlParser->parse($file->getContents()) ?? []); |
|
57
|
|
|
}; |
|
58
|
|
|
} |
|
59
|
2 |
|
return $config; |
|
60
|
2 |
|
}, []); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|