|
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, '/'); |
|
|
|
|
|
|
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
|
|
|
|