From f192d5b5a6be1c4b81017d9ebdf3cbbd70922fbb Mon Sep 17 00:00:00 2001 From: dantleech Date: Sat, 21 May 2016 11:27:56 +0100 Subject: [PATCH] Advanced YAML component usage --- components/yaml/introduction.rst | 52 ++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/components/yaml/introduction.rst b/components/yaml/introduction.rst index adb0d0956e6..99baa467f0a 100644 --- a/components/yaml/introduction.rst +++ b/components/yaml/introduction.rst @@ -185,7 +185,10 @@ If you only need to dump one array, you can use the use Symfony\Component\Yaml\Yaml; - $yaml = Yaml::dump($array, $inline); + $yaml = Yaml::dump($array); + +Array Expansion and Inlining +............................ The YAML format supports two kind of representation for arrays, the expanded one, and the inline one. By default, the dumper uses the inline @@ -201,7 +204,7 @@ representation to the inline one: .. code-block:: php - echo $dumper->dump($array, 1); + echo Yaml::dump($array, 1); .. code-block:: yaml @@ -210,7 +213,7 @@ representation to the inline one: .. code-block:: php - echo $dumper->dump($array, 2); + echo Yaml::dump($array, 2); .. code-block:: yaml @@ -219,6 +222,49 @@ representation to the inline one: foo: bar bar: baz +Indentation +........... + +By default the YAML component will use 4 spaces for indentation. This can be +changed using the second argument as follows:: + + // use 8 spaces for indentation + echo Yaml::dump($array, 2, 8); + +.. code-block:: yaml + + foo: bar + bar: + foo: bar + bar: baz + +Invalid Types and Object Serialization +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default the YAML component will encode any "unsupported" type (i.e. +resources and objects) as ``null``. + +Instead of encoding as ``null`` you can choose to throw an exception if an invalid +type is encountered in either the dumper or parser as follows:: + + // throw an exception if a resource or object is encoutered + Yaml::dump($data, 2, 4, true); + + // throw an exception if an encoded object is found in the YAML string + Yaml::parse($yaml, true); + +However, you can activate object support using the next argument:: + + $object = new \stdClass(); + $object->hello = 'goodbye'; + + $dumped = Yaml::dump($object, 2, 4, false, true); + // !!php/object:O:8:"stdClass":1:{s:5:"hello";s:7:"goodbye";} + + $parsed = Yaml::parse($dumped, false, true); + var_dump(is_object($parsed)); // true + echo $parsed->hello; // goodbye + .. _YAML: http://yaml.org/ .. _Packagist: https://packagist.org/packages/symfony/yaml .. _`YAML 1.2 version specification`: http://yaml.org/spec/1.2/spec.html