Skip to content

Instantly share code, notes, and snippets.

@Abdillah
Last active April 26, 2019 02:39
Show Gist options
  • Save Abdillah/6618e1ed33a88e2d4a36a3a97a4bd0b4 to your computer and use it in GitHub Desktop.
Save Abdillah/6618e1ed33a88e2d4a36a3a97a4bd0b4 to your computer and use it in GitHub Desktop.
Array to YAM-like
<?php
/**
* arr2yamlike - JSON-alternative format for human, readable and brief
*/
require_once __DIR__."/../vendor/autoload.php";
use Peridot\Leo\Interfaces\Assert;
/**
* Convert array of strings (possibly nested) into indent-formatted string
*
* Convert key into readable `Title Case` and value as it is. But if value
* is nested array, this function recurse. **Variable `$dept` is not a param!**
*
* @param int $indentation Indentation of the pretty string.
*/
function arr2yamlike($arr, $indentation = 3, $depth = 0) {
return join(PHP_EOL, array_map(function ($value, $key) use ($indentation, $depth) {
$key = ucwords(str_replace([ '-', '_' ], ' ', $key));
$value = (is_array($value))? ("\n" . humanifyArray($value, $indentation, $depth + 1)) : " $value";
return ($depth? str_pad(' ', $depth * $indentation) : '') . ucfirst($key) . " =$value";
}, array_values($arr), array_keys($arr)));
}
describe('arr2yamlike', function () {
beforeEach(function () {
$this->assert = new Assert;
});
it('should convert associative array into proper YAML-like output', function () {
$fixtures = [
[ [ 'key' => 'value' ], "Key = value" ],
[ [ 'key-dashed' => 'value' ], "Key Dashed = value" ],
[
[
'profile' => [
'name' => 'Zabaara',
'number' => '08291290129'
]
],
<<<EOS
Profile =
Name = Zabaara
Number = 08291290129
EOS
],
[
[
'profile' => [
'name' => 'Zabaara',
'number' => '08291290129'
],
'quarto' => 'Shenix',
],
<<<EOS
Profile =
Name = Zabaara
Number = 08291290129
Quarto = Shenix
EOS
],
];
foreach ($fixtures as $i => $fixture) {
$this->assert->equal(arr2yamlike($fixture[0], 4), $fixture[1]);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment