Passed
Pull Request — master (#1218)
by butschster
11:03
created

SingleFileStrategyLoader   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 19
c 1
b 0
f 0
dl 0
loc 46
ccs 22
cts 22
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 16 4
A __construct() 0 4 1
A has() 0 9 3
A findFile() 0 10 3
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