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 calledYaml::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 | useSymfony\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 containsTaggedValue
objects, they will be transformed into YAML tags:
1 2 3 4 5 6 7 8 | $config=array(newTaggedValue('foo',array('bar')),newTaggedValue('quz',array('baz')),);// The generated YAML code is:// - !foo [bar]// - !quz [baz] |