Passed
Pull Request — master (#389)
by Valentin
04:52
created

DirectoryLoader::loaderExtensions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Config\Loader;
13
14
use Spiral\Config\Exception\LoaderException;
15
use Spiral\Config\LoaderInterface;
16
17
final class DirectoryLoader implements LoaderInterface
18
{
19
    /** @var string */
20
    private $directory;
21
22
    /** @var FileLoaderInterface[] */
23
    private $loaders;
24
25
    /**
26
     * @param string $directory
27
     * @param array  $loaders
28
     */
29
    public function __construct(string $directory, array $loaders = [])
30
    {
31
        $this->directory = rtrim($directory, '/');
32
        $this->loaders = $loaders;
33
    }
34
35
    /**
36
     * @inheritdoc
37
     */
38
    public function has(string $section): bool
39
    {
40
        foreach ($this->loaderExtensions() as $extension) {
41
            $filename = sprintf('%s/%s.%s', $this->directory, $section, $extension);
42
            if (file_exists($filename)) {
43
                return true;
44
            }
45
        }
46
47
        return false;
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    public function load(string $section): array
54
    {
55
        foreach ($this->loaderExtensions() as $extension) {
56
            $filename = sprintf('%s/%s.%s', $this->directory, $section, $extension);
57
            if (!file_exists($filename)) {
58
                continue;
59
            }
60
61
            try {
62
                return $this->getLoader($extension)->loadFile($section, $filename);
63
            } catch (LoaderException $e) {
64
                throw new LoaderException("Unable to load config `{$section}`.", $e->getCode(), $e);
65
            }
66
        }
67
68
        throw new LoaderException("Unable to load config `{$section}`.");
69
    }
70
71
    private function loaderExtensions(): array
72
    {
73
        return array_keys($this->loaders);
74
    }
75
76
    /**
77
     * @param string $extension
78
     * @return FileLoaderInterface
79
     */
80
    private function getLoader(string $extension): FileLoaderInterface
81
    {
82
        return $this->loaders[$extension];
83
    }
84
}
85