|
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
|
|
|
* |
|
13
|
|
|
* Load configuration from the first found file in the provided directories. |
|
14
|
|
|
*/ |
|
15
|
|
|
final class SingleFileStrategyLoader implements LoaderInterface |
|
16
|
|
|
{ |
|
17
|
550 |
|
public function __construct( |
|
18
|
|
|
private readonly DirectoriesRepositoryInterface $directories, |
|
19
|
|
|
private readonly FileLoaderRegistry $fileLoader, |
|
20
|
550 |
|
) {} |
|
21
|
|
|
|
|
22
|
492 |
|
public function has(string $section): bool |
|
23
|
|
|
{ |
|
24
|
492 |
|
foreach ($this->fileLoader->getExtensions() as $extension) { |
|
25
|
492 |
|
if ($this->findFile($section, $extension) !== null) { |
|
26
|
447 |
|
return true; |
|
27
|
|
|
} |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
491 |
|
return false; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
471 |
|
public function load(string $section): array |
|
34
|
|
|
{ |
|
35
|
471 |
|
foreach ($this->fileLoader->getExtensions() as $extension) { |
|
36
|
471 |
|
$filename = $this->findFile($section, $extension); |
|
37
|
471 |
|
if ($filename === null) { |
|
38
|
5 |
|
continue; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
try { |
|
42
|
470 |
|
return $this->fileLoader->getLoader($extension)->loadFile($section, $filename); |
|
43
|
4 |
|
} catch (LoaderException $e) { |
|
44
|
4 |
|
throw new LoaderException("Unable to load config `{$section}`: {$e->getMessage()}", $e->getCode(), $e); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
1 |
|
throw new LoaderException(\sprintf('Unable to load config `%s`: no suitable loader found.', $section)); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
517 |
|
private function findFile(string $section, string $extension): ?string |
|
52
|
|
|
{ |
|
53
|
517 |
|
foreach ($this->directories as $directory) { |
|
54
|
517 |
|
$filename = \sprintf('%s/%s.%s', $directory, $section, $extension); |
|
55
|
517 |
|
if (\file_exists($filename)) { |
|
56
|
471 |
|
return $filename; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
496 |
|
return null; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|