Passed
Branch v0.2 (3b8de8)
by Freddie
05:06
created

loadEnvironmentConfigDefinitions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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