feature #21471 [Yaml] Allow dumping empty array as YAML sequence (c960657)

This PR was squashed before being merged into the 3.3-dev branch (closes #21471).

Discussion
----------

[Yaml] Allow dumping empty array as YAML sequence

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #9870, #15937, #16266
| License       | MIT
| Doc PR        |

PHP arrays are dumped as either YAML sequences or mappings, depending on whether the array has continuos integer keys or not.

An empty array is always dumped as a YAML mapping. Sometimes you want it dumped as a YAML sequence instead.

Commits
-------

87ffaf2b77 Bump version number
af7067c3cf Dump empty object as mapping
a6d94c1b53 [Yaml] Allow dumping empty array as YAML sequence
This commit is contained in:
Fabien Potencier 2017-02-19 15:22:09 -08:00
commit cf91b0af22
4 changed files with 27 additions and 2 deletions

View File

@ -6,6 +6,12 @@ CHANGELOG
* Omitting the key of a mapping is deprecated and will throw a `ParseException` in Symfony 4.0.
* Added support for dumping empty PHP arrays as YAML sequences:
```php
Yaml::dump([], 0, 0, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
```
3.2.0
-----

View File

@ -174,7 +174,7 @@ class Inline
}
if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
return self::dumpArray((array) $value, $flags);
return self::dumpArray((array) $value, $flags & ~Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
}
if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
@ -262,7 +262,7 @@ class Inline
private static function dumpArray($value, $flags)
{
// array
if ($value && !self::isHash($value)) {
if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) {
$output = array();
foreach ($value as $val) {
$output[] = self::dump($val, $flags);

View File

@ -247,6 +247,24 @@ EOF;
$this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, true);
}
public function testEmptyArray()
{
$dump = $this->dumper->dump(array());
$this->assertEquals('{ }', $dump);
$dump = $this->dumper->dump(array(), 0, 0, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
$this->assertEquals('[]', $dump);
$dump = $this->dumper->dump(array(), 9, 0, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
$this->assertEquals('[]', $dump);
$dump = $this->dumper->dump(new \ArrayObject(), 0, 0, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP);
$this->assertEquals('{ }', $dump);
$dump = $this->dumper->dump(new \stdClass(), 0, 0, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP);
$this->assertEquals('{ }', $dump);
}
/**
* @dataProvider getEscapeSequences
*/

View File

@ -29,6 +29,7 @@ class Yaml
const DUMP_OBJECT_AS_MAP = 64;
const DUMP_MULTI_LINE_LITERAL_BLOCK = 128;
const PARSE_CONSTANT = 256;
const DUMP_EMPTY_ARRAY_AS_SEQUENCE = 512;
/**
* @experimental in version 3.3