ConfigDefinitionLoader::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php declare(strict_types = 1);
2
3
namespace Simplex\DefinitionLoader;
4
5
use DI\ContainerBuilder;
6
7
final class ConfigDefinitionLoader implements DefinitionLoader
8
{
9
    private const CONFIG_FILENAME = 'config';
10
    private const CONFIG_FILE_EXTENSION = '.php';
11
12
    /** @var \SplFileInfo */
13
    private $configDirectory;
14
15
    /** @var string */
16
    private $environment;
17
18 5
    public function __construct(\SplFileInfo $configDirectory, string $environment)
19
    {
20 5
        if (!$configDirectory->isDir()) {
21 1
            throw new \LogicException("Invalid path to config directory " . $configDirectory->getRealPath());
22
        }
23
24 4
        $this->configDirectory = $configDirectory;
25 4
        $this->environment = $environment;
26 4
    }
27
28 4
    public function load(ContainerBuilder $containerBuilder): void
29
    {
30 4
        $this->loadRootConfigDefinitions($containerBuilder);
31 3
        $this->loadEnvironmentConfigDefinitions($containerBuilder);
32 3
    }
33
34 4
    private function loadRootConfigDefinitions(ContainerBuilder $containerBuilder): void
35
    {
36 4
        $rootConfigFile = new \SplFileInfo(
37 4
            $this->configDirectory->getPathname()
38 4
            . DIRECTORY_SEPARATOR
39 4
            . self::CONFIG_FILENAME
40 4
            . self::CONFIG_FILE_EXTENSION
41
        );
42
43 4
        if (!$rootConfigFile->isReadable()) {
44 1
            throw new \LogicException(
45 1
                "Config file not readable. Expected to find in " . $this->configDirectory->getRealPath()
46
            );
47
        }
48
49 3
        $containerBuilder->addDefinitions($rootConfigFile->getPathname());
50 3
    }
51
52 3
    private function loadEnvironmentConfigDefinitions(ContainerBuilder $containerBuilder): void
53
    {
54 3
        $envConfigFilePath = $this->configDirectory->getPathname()
55 3
            . DIRECTORY_SEPARATOR
56 3
            . self::CONFIG_FILENAME
57 3
            . '_'
58 3
            . $this->environment
59 3
            . self::CONFIG_FILE_EXTENSION;
60
61 3
        $envConfigFile = new \SplFileInfo($envConfigFilePath);
62
63 3
        if (!$envConfigFile->isFile()) {
64 1
            return;
65
        }
66
67 2
        $containerBuilder->addDefinitions($envConfigFile->getPathname());
68 2
    }
69
}
70