Completed
Push — master ( bf6ec7...65b5b4 )
by Arne
02:10
created

ConfigurationFileWriter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 7
c 0
b 0
f 0
lcom 1
cbo 3
dl 0
loc 58
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A writeConfigurationFile() 0 7 2
A buildConfigurationFile() 0 21 3
A getDefaultConfiguration() 0 6 1
A getDefaultVaultConfiguration() 0 6 1
1
<?php
2
3
namespace Storeman\Config;
4
5
use Storeman\ArrayUtils;
6
7
class ConfigurationFileWriter
8
{
9
    /**
10
     * @param Configuration $configuration
11
     * @param string $path File path to write the configuration file to.
12
     * @param bool $skipDefaults If true only settings that do not match the default are written.
13
     */
14
    public function writeConfigurationFile(Configuration $configuration, string $path, bool $skipDefaults = true): void
15
    {
16
        if (!file_put_contents($path, $this->buildConfigurationFile($configuration, $skipDefaults)))
17
        {
18
            throw new \RuntimeException("Cannot write configuration file to {$path}");
19
        }
20
    }
21
22
    /**
23
     * Serializes the given configuration to the content of an equivalent configuration file.
24
     *
25
     * @param Configuration $configuration
26
     * @param bool $skipDefaults If true only settings that do not match the default are written.
27
     * @return string
28
     */
29
    public function buildConfigurationFile(Configuration $configuration, bool $skipDefaults = true): string
30
    {
31
        $configArray = $configuration->getArrayCopy();
32
33
        if ($skipDefaults)
34
        {
35
            $nonDefaults = ArrayUtils::recursiveArrayDiff($configArray, $this->getDefaultConfiguration($configuration)->getArrayCopy());
36
37
            $vaultConfigs = [];
38
            foreach ($configuration->getVaults() as $vaultConfiguration)
39
            {
40
                $vaultConfigs[] = ArrayUtils::recursiveArrayDiff($vaultConfiguration->getArrayCopy(), $this->getDefaultVaultConfiguration($vaultConfiguration)->getArrayCopy());
41
            }
42
43
            $nonDefaults['vaults'] = $vaultConfigs;
44
45
            $configArray = $nonDefaults;
46
        }
47
48
        return json_encode($configArray, JSON_PRETTY_PRINT);
49
    }
50
51
    protected function getDefaultConfiguration(Configuration $configuration): Configuration
52
    {
53
        $class = get_class($configuration);
54
55
        return new $class;
56
    }
57
58
    protected function getDefaultVaultConfiguration(VaultConfiguration $vaultConfiguration): VaultConfiguration
59
    {
60
        $class = get_class($vaultConfiguration);
61
62
        return new $class($this->getDefaultConfiguration($vaultConfiguration->getConfiguration()));
63
    }
64
}
65