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