diff --git a/encoder/network.php b/encoder/network.php index 8bf442b..be72ec0 100755 --- a/encoder/network.php +++ b/encoder/network.php @@ -167,8 +167,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { } } - $yaml = yaml($netplan); - file_put_contents('/var/www/50-cloud-init.yaml', $yaml); + file_put_contents('/var/www/50-cloud-init.yaml', netplan_yaml($netplan)); } } diff --git a/encoder/static.php b/encoder/static.php index 0bff5ee..965b50b 100755 --- a/encoder/static.php +++ b/encoder/static.php @@ -133,21 +133,47 @@ function build_interface(array $cfg, string $type): array return $out; } -function yaml(array $data, int $indent = 0): string +function netplan_yaml(array $data, int $indent = 0): string { $out = ''; $pad = str_repeat(' ', $indent); - foreach ($data as $k => $v) { - if ($v instanceof stdClass) { - $out .= "{$pad}{$k}: {}\n"; - } elseif (is_array($v)) { - $out .= "{$pad}{$k}:\n"; - $out .= yaml($v, $indent + 1); - } else { - $out .= "{$pad}{$k}: {$v}\n"; + foreach ($data as $key => $value) { + + /* Empty map */ + if ($value instanceof stdClass) { + $out .= "{$pad}{$key}: {}\n"; + continue; } + + /* Boolean */ + if (is_bool($value)) { + $out .= "{$pad}{$key}: " . ($value ? 'true' : 'false') . "\n"; + continue; + } + + /* Scalar */ + if (!is_array($value)) { + $out .= "{$pad}{$key}: {$value}\n"; + continue; + } + + /* Numeric array (list) */ + if (array_keys($value) === range(0, count($value) - 1)) { + $out .= "{$pad}{$key}:\n"; + foreach ($value as $item) { + $out .= is_bool($item) + ? "{$pad} - " . ($item ? 'true' : 'false') . "\n" + : "{$pad} - {$item}\n"; + } + continue; + } + + /* Mapping */ + $out .= "{$pad}{$key}:\n"; + $out .= netplan_yaml($value, $indent + 1); } + return $out; }