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

DirectoryLoader   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 33.33%

Importance

Changes 0
Metric Value
wmc 10
eloc 19
c 0
b 0
f 0
dl 0
loc 52
ccs 7
cts 21
cp 0.3333
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 16 4
A getLoader() 0 3 1
A has() 0 10 3
A loaderExtensions() 0 3 1
A __construct() 0 5 1
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