Passed
Pull Request — master (#1218)
by butschster
11:03
created

DirectoryLoader::load()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 16
ccs 0
cts 9
cp 0
rs 9.9666
cc 4
nc 4
nop 1
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Config\Loader;
6
7
use Spiral\Config\Exception\LoaderException;
8
use Spiral\Config\LoaderInterface;
9
10
/**
11
 * @internal
12
 * @deprecated Use {@see SingleFileStrategyLoader} instead. Will be removed in 4.0.
13
 */
14
final class DirectoryLoader implements LoaderInterface
15
{
16
    private readonly string $directory;
17
18
    /**
19
     * @param FileLoaderInterface[] $loaders
20
     */
21 32
    public function __construct(
22
        string $directory,
23
        private readonly array $loaders = [],
24
    ) {
25 32
        $this->directory = \rtrim($directory, '/');
0 ignored issues
show
Bug introduced by
The property directory is declared read-only in Spiral\Config\Loader\DirectoryLoader.
Loading history...
26
    }
27
28 32
    public function has(string $section): bool
29
    {
30 32
        foreach ($this->loaderExtensions() as $extension) {
31
            $filename = \sprintf('%s/%s.%s', $this->directory, $section, $extension);
32
            if (\file_exists($filename)) {
33
                return true;
34
            }
35
        }
36
37 32
        return false;
38
    }
39
40
    public function load(string $section): array
41
    {
42
        foreach ($this->loaderExtensions() as $extension) {
43
            $filename = \sprintf('%s/%s.%s', $this->directory, $section, $extension);
44
            if (!\file_exists($filename)) {
45
                continue;
46
            }
47
48
            try {
49
                return $this->getLoader($extension)->loadFile($section, $filename);
50
            } catch (LoaderException $e) {
51
                throw new LoaderException("Unable to load config `{$section}`: {$e->getMessage()}", $e->getCode(), $e);
52
            }
53
        }
54
55
        throw new LoaderException(\sprintf('Unable to load config `%s`: no suitable loader found.', $section));
56
    }
57
58 32
    private function loaderExtensions(): array
59
    {
60 32
        return \array_keys($this->loaders);
61
    }
62
63
    private function getLoader(string $extension): FileLoaderInterface
64
    {
65
        return $this->loaders[$extension];
66
    }
67
}
68