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
|
|
|
|