Skip to content
Snippets Groups Projects
FanConfig.php 2 KiB
Newer Older
Thomas Flori's avatar
Thomas Flori committed
<?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;
    }
}