8000 [Yaml] add option to dump objects as maps · dunglas/symfony@3941d2e · GitHub
[go: up one dir, main page]

Skip to content

Commit 3941d2e

Browse files
committed
[Yaml] add option to dump objects as maps
1 parent 48f05ec commit 3941d2e

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
@@ -159,6 +159,10 @@ public static function dump($value, $flags = 0)
159159
return '!php/object:'.serialize($value);
160160
}
161161

162+
if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
163+
return self::dumpArray((array) $value, $flags);
164+
}
165+
162166
if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
163167
throw new DumpException('Object support when dumping a YAML file has been disabled.');
164168
}

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
@@ -26,6 +26,7 @@ class Yaml
2626
const PARSE_OBJECT_FOR_MAP = 8;
2727
const DUMP_EXCEPTION_ON_INVALID_TYPE = 16;
2828
const PARSE_DATETIME = 32;
29+
const DUMP_OBJECT_AS_MAP = 64;
2930

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

0 commit comments

Comments
 (0)
0