New in Symfony 3.3: Custom YAML tags

Contributed by
Guilhem Niot
in #21194.

The YAML format is well known for being simple and readable, but under the hood it defines lots of advanced features for complex needs. One of those features are YAML tags, which are primarily used to define explicit data types.

The Symfony Yaml component already supports several tags, such as !!binary for storing binary data, and !php/const: for referring to PHP constants. In Symfony 3.3 you now can define your own YAML tags thanks to a new flag called Yaml::PARSE_CUSTOM_TAGS.

Custom tags are arbitrary strings that start with the ! character, such as the !my_tag value in the following example:

1
!my_tag { foo: bar }

Use the following PHP code to parse it:

1
2
3
4
5
6
7
8
use Symfony\Component\Yaml\Yaml;

$yaml = "!my_tag { foo: bar }";
$config = Yaml::parse($yaml, Yaml::PARSE_CUSTOM_TAGS);


$tag = $config->getTag();     // $tag = 'my_tag'
$value = $config->getValue(); // $value = array('foo' => 'bar')

The semantics of the YAML tags depend on each application, so the parser wraps those values in a generic Symfony\Component\Yaml\Tag\TaggedValue class. In the above example, the $config variable now contains:

1
TaggedValue('my_tag', array('foo' => 'bar'));

The support for YAML tags goes both ways, so if your PHP code contains TaggedValue objects, they will be transformed into YAML tags:

1
2
3
4
5
6
7
8
$config = array(
    new TaggedValue('foo', array('bar')),
    new TaggedValue('quz', array('baz')),
);

// The generated YAML code is:
// - !foo [bar]
// - !quz [baz]

Comments

As Yaml tags are not well known, I suggest a whole article on tags and their usage, with some use-cases, because I personally don't understand why to use them :/
Missing `new` in the third code snippet :)
@Kamil I've reworded the third snippet to bette explain that we're showing what the $config variable contains.
I agree with Alex Rock, it lacks of a concrete example.
Furthermore, can we use it to construct objects ?
@Alexandre It is used for the new iterator feature of the di component.
It does not build the object for you, it does return a TaggedValue value that you have to convert to whatever you want.

Important to note : tagged scalars are not supported yet because of BC but they will be in 4.0.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.