Passed
Push — master ( 7dc569...e9ad93 )
by Mr
08:03
created

CratesConfigLoader::expandPath()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 1
dl 0
loc 13
ccs 0
cts 6
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/boot 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\Boot\Config;
10
11
use Daikon\Config\ConfigLoaderInterface;
12
use Daikon\Config\YamlConfigLoader;
13
use Stringy\Stringy;
14
15
final class CratesConfigLoader implements ConfigLoaderInterface
16
{
17
    private YamlConfigLoader $yamlLoader;
18
19
    private array $dirPrefixes;
20
21
    public function __construct(array $dirPrefixes, YamlConfigLoader $yamlLoader = null)
22
    {
23
        $this->yamlLoader = $yamlLoader ?? new YamlConfigLoader;
24
        $this->dirPrefixes = $dirPrefixes;
25
    }
26
27
    public function load(array $locations, array $sources): array
28
    {
29
        $config = [];
30
        foreach ($this->yamlLoader->load($locations, $sources) as $crateName => $crateConfig) {
31
            //@todo improve configuration loading for missing values
32
            $configDir = $crateConfig['config_dir'] ?? '';
33
            $migrationDir = $crateConfig['migration_dir'] ?? '';
34
            $fixtureDir = $crateConfig['fixture_dir'] ?? '';
35
            $crateConfig['config_dir'] = $this->expandPath($configDir);
36
            $crateConfig['migration_dir'] = $this->expandPath($migrationDir);
37
            $crateConfig['fixture_dir'] = $this->expandPath($fixtureDir);
38
            $config[$crateName] = $crateConfig;
39
        }
40
41
        return $config;
42
    }
43
44
    private function expandPath(string $path): string
45
    {
46
        if (Stringy::create($path)->startsWith('/')) {
47
            return $path;
48
        }
49
50
        $search = array_keys($this->dirPrefixes);
51
        $replace = array_map(
52
            fn(string $path): string => Stringy::create($path)->endsWith('/') ? $path : "$path/",
53
            array_values($this->dirPrefixes)
54
        );
55
56
        return str_replace($search, $replace, $path);
57
    }
58
}
59