[Yaml] add option to dump objects as maps
This commit is contained in:
parent
48f05ecad2
commit
3941d2ee4b
@ -159,6 +159,10 @@ class Inline
|
||||
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.');
|
||||
}
|
||||
|
@ -276,6 +276,46 @@ EOF;
|
||||
'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
|
||||
|
@ -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.
|
||||
|
Reference in New Issue
Block a user