YamlConfigProvider   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 8
eloc 28
c 3
b 0
f 2
dl 0
loc 76
ccs 0
cts 28
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A fromFile() 0 33 4
A __construct() 0 3 1
A __invoke() 0 5 1
A fromFiles() 0 8 2
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