Passed
Push — master ( 81e780...d41685 )
by Mariano
03:19 queued 27s
created

ConfigBuilder   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 29
c 1
b 0
f 0
dl 0
loc 54
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getDefaultExpectationsDir() 0 5 1
A __construct() 0 11 2
A build() 0 23 4
1
<?php
2
3
namespace Mcustiel\Phiremock\Server\Utils\Config;
4
5
use Mcustiel\Phiremock\Server\Cli\Options\ExpectationsDirectory;
6
use Mcustiel\Phiremock\Server\Utils\HomePathService;
7
8
class ConfigBuilder
9
{
10
    private const DEFAULT_IP = '0.0.0.0';
11
    private const DEFAULT_PORT = 8086;
12
    private const DEFAULT_EXPECTATIONS_DIR = '[USER_HOME_PATH]/.phiremock/expectations';
13
14
    private static $defaultConfig;
15
16
    /** @var Directory */
17
    private $configPath;
18
19
    public function __construct(Directory $configPath)
20
    {
21
        if (self::$defaultConfig === null) {
22
            self::$defaultConfig = [
23
                'port'             => self::DEFAULT_PORT,
24
                'ip'               => self::DEFAULT_IP,
25
                'expectations-dir' => self::getDefaultExpectationsDir()->asString(),
26
                'debug'            => false,
27
            ];
28
        }
29
        $this->configPath = $configPath;
30
    }
31
32
    public function build(array $cliConfig): Config
33
    {
34
        $config = self::$defaultConfig;
35
36
        $fileConfiguration = [];
37
38
        $configFiles = ['.phiremock', '.phiremock.dist'];
39
40
        foreach ($configFiles as $configFileName) {
41
            $configFilePath = $this->configPath->getFullSubpathAsString($configFileName);
42
            if (file_exists($configFilePath)) {
43
                $fileConfiguration = require $configFilePath;
44
                break;
45
            }
46
        }
47
        $extraKeys = array_diff_key($fileConfiguration, self::$defaultConfig);
48
        if (!empty($extraKeys)) {
49
            throw new \DomainException('Extra keys in configuration file: ' . implode(',', $extraKeys));
50
        }
51
52
        var_dump($config, $fileConfiguration, $cliConfig);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($config, $fileConfiguration, $cliConfig) looks like debug code. Are you sure you do not want to remove it?
Loading history...
53
54
        return new Config(array_replace($config, $fileConfiguration, $cliConfig));
55
    }
56
57
    public static function getDefaultExpectationsDir(): ExpectationsDirectory
58
    {
59
        return new ExpectationsDirectory(
60
            HomePathService::getHomePath()->getFullSubpathAsString(
61
                '.phiremock' . \DIRECTORY_SEPARATOR . 'expectations'
62
            )
63
        );
64
    }
65
}
66