Passed
Push — master ( abee1f...edc958 )
by Kirill
03:08
created

DirectoryLoader   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 26
dl 0
loc 73
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 16 4
A getLoader() 0 7 2
A has() 0 10 3
A __construct() 0 4 1
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
use Spiral\Core\FactoryInterface;
17
18
final class DirectoryLoader implements LoaderInterface
19
{
20
    public const LOADERS = [
21
        'php'  => PhpLoader::class,
22
        'json' => JsonLoader::class,
23
    ];
24
25
    /** @var string */
26
    private $directory;
27
28
    /** @var FactoryInterface */
29
    private $factory;
30
31
    /** @var FileLoaderInterface[] */
32
    private $loaders = [];
33
34
    /**
35
     * @param string           $directory
36
     * @param FactoryInterface $factory
37
     */
38
    public function __construct(string $directory, FactoryInterface $factory)
39
    {
40
        $this->directory = rtrim($directory, '/');
41
        $this->factory = $factory;
42
    }
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public function has(string $section): bool
48
    {
49
        foreach (static::LOADERS as $extension => $class) {
50
            $filename = sprintf('%s/%s.%s', $this->directory, $section, $extension);
51
            if (file_exists($filename)) {
52
                return true;
53
            }
54
        }
55
56
        return false;
57
    }
58
59
    /**
60
     * @inheritdoc
61
     */
62
    public function load(string $section): array
63
    {
64
        foreach (static::LOADERS as $extension => $class) {
65
            $filename = sprintf('%s/%s.%s', $this->directory, $section, $extension);
66
            if (!file_exists($filename)) {
67
                continue;
68
            }
69
70
            try {
71
                return $this->getLoader($extension)->loadFile($section, $filename);
72
            } catch (LoaderException $e) {
73
                throw new LoaderException("Unable to load config `{$section}`.", $e->getCode(), $e);
74
            }
75
        }
76
77
        throw new LoaderException("Unable to load config `{$section}`.");
78
    }
79
80
    /**
81
     * @param string $extension
82
     * @return FileLoaderInterface
83
     */
84
    private function getLoader(string $extension): FileLoaderInterface
85
    {
86
        if (isset($this->loaders[$extension])) {
87
            return $this->loaders[$extension];
88
        }
89
90
        return $this->loaders[$extension] = $this->factory->make(static::LOADERS[$extension]);
91
    }
92
}
93