Created
September 13, 2017 10:20
-
-
Save bouiboui/57b3bc207234b368f68d7b5b4d629b3f to your computer and use it in GitHub Desktop.
Creates a YAML description from a JSON payload (replace $data by your JSON payload)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function formatLine(array $items, $indent) | |
{ | |
$spaces = ''; | |
while ($indent--) { | |
$spaces .= ' '; | |
} | |
return PHP_EOL . | |
implode(PHP_EOL, | |
array_map(function ($item) use ($spaces) { | |
return $spaces . $item; | |
}, $items)) | |
. PHP_EOL; | |
} | |
function getFormatter($key, $value, $indent = 0) | |
{ | |
$keyLine = null !== $key ? $key . ':' : ''; | |
switch ($type = gettype($value)) { | |
case 'double': | |
echo formatLine([ | |
$keyLine, | |
' type: number', | |
' format: float', | |
' example: ' . $value | |
], $indent); | |
break; | |
case 'integer': | |
echo formatLine([ | |
$keyLine, | |
' type: number', | |
' example: ' . $value | |
], $indent); | |
break; | |
case 'string': | |
echo formatLine([ | |
$keyLine, | |
' type: string', | |
' example: "' . $value . '"' | |
], $indent); | |
break; | |
case 'boolean': | |
echo formatLine([ | |
$keyLine, | |
' type: boolean', | |
' example: ' . (string)$value | |
], $indent); | |
break; | |
case 'object': | |
echo formatLine([ | |
$keyLine, | |
' type: object', | |
' properties: ', | |
], $indent); | |
foreach ($value as $key2 => $value2) { | |
getFormatter($key2, $value2, $indent + 4); | |
} | |
break; | |
case 'array': | |
$lineItems = [ | |
$keyLine, | |
' type: array' | |
]; | |
if (count($value)) { | |
$lineItems[] = ' items: '; | |
} | |
echo formatLine($lineItems, $indent); | |
$oldKey = PHP_INT_MAX; | |
foreach ($value as $key2 => $value2) { | |
$finalKey = is_int($key2) ? null : $key2; | |
if ($finalKey !== $oldKey) { | |
getFormatter($finalKey, $value2, $indent + 2); | |
$oldKey = $finalKey; | |
} | |
} | |
break; | |
default: | |
throw new Exception($type . ' unknown'); | |
} | |
} | |
function toYaml($data) | |
{ | |
foreach ($data as $key => $value) { | |
getFormatter($key, $value); | |
} | |
} | |
$data = <<<JSON | |
{ | |
"string": "abcd", | |
"integer": 123, | |
"array": [1,2,3], | |
"object": { | |
"string": "abcd", | |
"integer": 123, | |
"array": [1, 2, 3] | |
} | |
} | |
JSON; | |
toYaml(json_decode($data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The gist returns: