From 3941d2ee4bf5de72ec94a025c4e28093ddfc44ab Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 8 Feb 2016 18:17:53 +0100 Subject: [PATCH] [Yaml] add option to dump objects as maps --- src/Symfony/Component/Yaml/Inline.php | 4 ++ .../Component/Yaml/Tests/DumperTest.php | 40 +++++++++++++++++++ src/Symfony/Component/Yaml/Yaml.php | 1 + 3 files changed, 45 insertions(+) diff --git a/src/Symfony/Component/Yaml/Inline.php b/src/Symfony/Component/Yaml/Inline.php index b11e03147cd7..071aaf5a6cdc 100644 --- a/src/Symfony/Component/Yaml/Inline.php +++ b/src/Symfony/Component/Yaml/Inline.php @@ -159,6 +159,10 @@ public static function dump($value, $flags = 0) return '!php/object:'.serialize($value); } + if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) { + return self::dumpArray((array) $value, $flags); + } + if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { throw new DumpException('Object support when dumping a YAML file has been disabled.'); } diff --git a/src/Symfony/Component/Yaml/Tests/DumperTest.php b/src/Symfony/Component/Yaml/Tests/DumperTest.php index 7a110aa57794..b55b17345c69 100644 --- a/src/Symfony/Component/Yaml/Tests/DumperTest.php +++ b/src/Symfony/Component/Yaml/Tests/DumperTest.php @@ -276,6 +276,46 @@ public function getEscapeSequences() 'paragraph-separator' => array("\t\\P", '"\t\\\\P"'), ); } + + /** + * @dataProvider objectAsMapProvider + */ + public function testDumpObjectAsMap($object, $expected) + { + + $yaml = $this->dumper->dump($object, 0, 0, Yaml::DUMP_OBJECT_AS_MAP); + + $this->assertEquals($expected, Yaml::parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP)); + } + + public function objectAsMapProvider() + { + $tests = array(); + + $bar = new \stdClass(); + $bar->class = 'classBar'; + $bar->args = array('bar'); + $zar = new \stdClass(); + $foo = new \stdClass(); + $foo->bar = $bar; + $foo->zar = $zar; + $object = new \stdClass(); + $object->foo = $foo; + $tests['stdClass'] = array($object, $object); + + $arrayObject = new \ArrayObject(); + $arrayObject['foo'] = 'bar'; + $arrayObject['baz'] = 'foobar'; + $parsedArrayObject = new \stdClass(); + $parsedArrayObject->foo = 'bar'; + $parsedArrayObject->baz = 'foobar'; + $tests['ArrayObject'] = array($arrayObject, $parsedArrayObject); + + $a = new A(); + $tests['arbitrary-object'] = array($a, null); + + return $tests; + } } class A diff --git a/src/Symfony/Component/Yaml/Yaml.php b/src/Symfony/Component/Yaml/Yaml.php index 9c321a81322e..4b784e35687a 100644 --- a/src/Symfony/Component/Yaml/Yaml.php +++ b/src/Symfony/Component/Yaml/Yaml.php @@ -26,6 +26,7 @@ class Yaml const PARSE_OBJECT_FOR_MAP = 8; const DUMP_EXCEPTION_ON_INVALID_TYPE = 16; const PARSE_DATETIME = 32; + const DUMP_OBJECT_AS_MAP = 64; /** * Parses YAML into a PHP value.