Completed
Push — master ( e2f78c...1af02f )
by Arne
03:18
created

getDefaultVaultConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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