Skip to content

Commit 80f0b66

Browse files
committed
[Yaml] add option to dump objects as maps
1 parent 7848a46 commit 80f0b66

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

src/Symfony/Component/Yaml/Inline.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,10 @@ public static function dump($value, $flags = 0)
155155
return '!php/object:'.serialize($value);
156156
}
157157

158+
if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
159+
return self::dumpArray((array) $value, $flags);
160+
}
161+
158162
if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
159163
throw new DumpException('Object support when dumping a YAML file has been disabled.');
160164
}

src/Symfony/Component/Yaml/Tests/DumperTest.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,46 @@ public function getEscapeSequences()
276276
'paragraph-separator' => array("\t\\P", '"\t\\\\P"'),
277277
);
278278
}
279+
280+
/**
281+
* @dataProvider objectAsMapProvider
282+
*/
283+
public function testDumpObjectAsMap($object, $expected)
284+
{
285+
286+
$yaml = $this->dumper->dump($object, 0, 0, Yaml::DUMP_OBJECT_AS_MAP);
287+
288+
$this->assertEquals($expected, Yaml::parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP));
289+
}
290+
291+
public function objectAsMapProvider()
292+
{
293+
$tests = array();
294+
295+
$bar = new \stdClass();
296+
$bar->class = 'classBar';
297+
$bar->args = array('bar');
298+
$zar = new \stdClass();
299+
$foo = new \stdClass();
300+
$foo->bar = $bar;
301+
$foo->zar = $zar;
302+
$object = new \stdClass();
303+
$object->foo = $foo;
304+
$tests['stdClass'] = array($object, $object);
305+
306+
$arrayObject = new \ArrayObject();
307+
$arrayObject['foo'] = 'bar';
308+
$arrayObject['baz'] = 'foobar';
309+
$parsedArrayObject = new \stdClass();
310+
$parsedArrayObject->foo = 'bar';
311+
$parsedArrayObject->baz = 'foobar';
312+
$tests['ArrayObject'] = array($arrayObject, $parsedArrayObject);
313+
314+
$a = new A();
315+
$tests['arbitrary-object'] = array($a, null);
316+
317+
return $tests;
318+
}
279319
}
280320

281321
class A

src/Symfony/Component/Yaml/Yaml.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ class Yaml
2525
const PARSE_OBJECT = 4;
2626
const PARSE_OBJECT_FOR_MAP = 8;
2727
const DUMP_EXCEPTION_ON_INVALID_TYPE = 16;
28+
const DUMP_OBJECT_AS_MAP = 32;
2829

2930
/**
3031
* Parses YAML into a PHP value.

0 commit comments

Comments
 (0)