Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace App;
class FanConfig
{
protected $path = '/dev/null';
protected $fans = [];
public function hasFans(): bool
{
return count($this->fans) > 0;
}
public function setFans(array $fans): self
{
// do we validate that? or was it validated already?
$this->fans = $fans;
return $this;
}
public static function readConfig(string $path): self
{
$self = new FanConfig();
$self->path = $path;
if (!file_exists($path)) {
return $self;
}
$cfg = include($path);
// validate config
if (!is_array($cfg)) {
throw new \InvalidArgumentException('given configuration is not a fan-ctrl config');
}
$self = new FanConfig();
$self->path = $path;
$self->fans = $cfg['fans'] ?? [];
return $self;
}
public function save()
{
// ob_start();
// $fans = $this->fans;
// include __DIR__ . '/../resources/config-template.php';
// $code = ob_get_clean();
$code = '<?php' . PHP_EOL . PHP_EOL .
'return ' . $this->exportArray([
'fans' => $this->fans,
]) . ';' . PHP_EOL;
file_put_contents($this->path, $code);
// exec(__DIR__ . '/../vendor/bin/php-cs-fixer fix ' . $this->path . ' --rules');
}
protected function exportArray(array $array, $indentation = 0)
{
$indexed = array_keys($array) === array_keys(array_keys($array));
$indentation += 4;
$var = '[' . PHP_EOL;
foreach ($array as $key => $value) {
$var .= str_repeat(' ', $indentation);
if (!$indexed) {
$var .= var_export($key, true) . ' => ';
}
$var .= is_array($value) ? $this->exportArray($value, $indentation) : var_export($value, true);
$var .= ',' . PHP_EOL;
}
$indentation -= 4;
$var .= str_repeat(' ', $indentation) . ']';
return $var;
}
}