|
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
|
|
|
|