Skip to content

Commit 6a17d49

Browse files
committed
Advanced YAML component usage
1 parent bbec4cc commit 6a17d49

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

components/yaml/introduction.rst

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,10 @@ If you only need to dump one array, you can use the
185185
186186
use Symfony\Component\Yaml\Yaml;
187187
188-
$yaml = Yaml::dump($array, $inline);
188+
$yaml = Yaml::dump($array);
189+
190+
Array Expansion and Inlining
191+
""""""""""""""""""""""""""""
189192

190193
The YAML format supports two kind of representation for arrays, the expanded
191194
one, and the inline one. By default, the dumper uses the inline
@@ -219,6 +222,55 @@ representation to the inline one:
219222
foo: bar
220223
bar: baz
221224
225+
Indentation
226+
"""""""""""
227+
228+
By default the YAML component will use 4 spaces for indentation, this can be
229+
changed using the second argument as follows:
230+
231+
.. code-block:: php
232+
233+
// use 8 spaces for indentation
234+
echo $dumper->dump($array, 2, 8);
235+
236+
.. code-block:: yaml
237+
238+
foo: bar
239+
bar:
240+
foo: bar
241+
bar: baz
242+
243+
Invalid Types and Object Serialization
244+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
245+
246+
By default the YAML component will encode any "unsupported" type (i.e.
247+
resources and objects) as a string value "null".
248+
249+
Instead of encoding as null you can choose to throw an exception if an invalid
250+
type is encoutered in either the dumper or parser as follows:
251+
252+
.. code-block:: php
253+
254+
// throw an exception if a resource or object is encoutered
255+
$dumper->dump($data, 2, 4, true);
256+
257+
// throw an exception if an encoded object is found in the YAML string
258+
$parser->parse($yaml, true); // throw an exception
259+
260+
However you can activate object support using the next argument:
261+
262+
.. code-block:: php
263+
264+
$object = new \stdClass();
265+
$object->hello = 'goodbye';
266+
267+
$dumoed = $dumper->dump($object, 2, 0, false, true);
268+
// !!php/object:O:8:"stdClass":1:{s:5:"hello";s:7:"goodbye";}
269+
270+
$parsed = $parser->parse($dumped, false, true);
271+
is_object($parsed); // true
272+
echo $parsed->hello; // goodbye
273+
222274
.. _YAML: http://yaml.org/
223275
.. _Packagist: https://packagist.org/packages/symfony/yaml
224276
.. _`YAML 1.2 version specification`: http://yaml.org/spec/1.2/spec.html

0 commit comments

Comments
 (0)