Skip to content

Instantly share code, notes, and snippets.

@bouiboui
Created September 13, 2017 10:20
Show Gist options
  • Save bouiboui/57b3bc207234b368f68d7b5b4d629b3f to your computer and use it in GitHub Desktop.
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)
<?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));
@bouiboui
Copy link
Author

The gist returns:

string:
  type: string
  example: "abcd"

integer:
  type: number
  example: 123

array:
  type: array
  items: 

  
    type: number
    example: 1

object:
  type: object
  properties: 

    string:
      type: string
      example: "abcd"

    integer:
      type: number
      example: 123

    array:
      type: array
      items: 

      
        type: number
        example: 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment