This commit is contained in:
Anton Bakai 2016-05-24 23:58:05 +03:00 committed by Nicolas Grekas
parent 53b7236fa8
commit 7d78196d0c
3 changed files with 45 additions and 7 deletions

View File

@ -58,7 +58,7 @@ class Dumper
if ($inline <= 0 || !is_array($input) || empty($input)) {
$output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
} else {
$isAHash = array_keys($input) !== range(0, count($input) - 1);
$isAHash = Inline::isHash($input);
foreach ($input as $key => $value) {
$willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);

View File

@ -145,6 +145,28 @@ class Inline
}
}
/**
* Check if given array is hash or just normal indexed array.
*
* @internal
*
* @param array $value The PHP array to check
*
* @return bool true if value is hash array, false otherwise
*/
public static function isHash(array $value)
{
$expectedKey = 0;
foreach ($value as $key => $val) {
if ($key !== $expectedKey++) {
return true;
}
}
return false;
}
/**
* Dumps a PHP array to a YAML string.
*
@ -157,11 +179,7 @@ class Inline
private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
{
// array
$keys = array_keys($value);
$keysCount = count($keys);
if ((1 === $keysCount && '0' == $keys[0])
|| ($keysCount > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) === $keysCount * ($keysCount - 1) / 2)
) {
if ($value && !self::isHash($value)) {
$output = array();
foreach ($value as $val) {
$output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport);
@ -170,7 +188,7 @@ class Inline
return sprintf('[%s]', implode(', ', $output));
}
// mapping
// hash
$output = array();
foreach ($value as $key => $val) {
$output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport));

View File

@ -169,6 +169,24 @@ class InlineTest extends \PHPUnit_Framework_TestCase
Inline::parse('{ foo: * #foo }');
}
/**
* @dataProvider getDataForIsHash
*/
public function testIsHash($array, $expected)
{
$this->assertSame($expected, Inline::isHash($array));
}
public function getDataForIsHash()
{
return array(
array(array(), false),
array(array(1, 2, 3), false),
array(array(2 => 1, 1 => 2, 0 => 3), true),
array(array('foo' => 1, 'bar' => 2), true),
);
}
protected function getTestsForParse()
{
return array(
@ -296,6 +314,8 @@ class InlineTest extends \PHPUnit_Framework_TestCase
'[foo, { bar: foo, foo: [foo, { bar: foo }] }, [foo, { bar: foo }]]' => array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo'))),
'[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']' => array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container'),
'{ foo: { bar: { 1: 2, baz: 3 } } }' => array('foo' => array('bar' => array(1 => 2, 'baz' => 3))),
);
}
}