Symfony has been reducing the need for configuration in applications for several years now. Thanks to PHP attributes, you can now configure most things alongside the relevant code, removing the need for external files and formats like YAML. However, YAML remains an important configuration format in Symfony and beyond. That's why Symfony 7.3 added several new features to the Yaml component.
Dumping Quoted Strings
When dumping string contents, they are only quoted by default when they contain unsafe values (e.g. white spaces). Otherwise, they are dumped unquoted because that is more compact and still valid YAML:
1 2 3 4
use Symfony\Component\Yaml\Yaml;
$data = ['data' => ['OTEL_EXPORTER_OTLP_PROTOCOL' => 'grpc']];
$yaml = Yaml::dump($data);
This code outputs:
1 2
data:
OTEL_EXPORTER_OTLP_PROTOCOL: grpc
This is technically valid YAML, but some strict parsers will warn you about any
unquoted string contents (e.g. when dumping ConfigMap
entries in Kubernetes).
That's why Symfony 7.3 added a new flag to make this behavior configurable:
1
$yaml = Yaml::dump($data, 2, 4, Yaml::DUMP_FORCE_DOUBLE_QUOTES_ON_VALUES);
This code now outputs:
1 2
data:
OTEL_EXPORTER_OTLP_PROTOCOL: "grpc"
Dumping Compact Collections of Maps
Consider the following data structure representing a list of associative arrays in PHP:
1 2 3 4
$data = ['planets' => [
['name' => 'Mercury', 'distance' => 57910000],
['name' => 'Jupiter', 'distance' => 778500000],
];
When dumping this data as YAML, the result is:
1 2 3 4 5 6 7
planets:
-
name: Mercury
distance: 57910000
-
name: Jupiter
distance: 778500000
In Symfony 7.3, a new flag was added to configure this behavior and allow you to generate more compact dumps:
1
$yaml = Yaml::dump($data, 2, 4, Yaml::DUMP_COMPACT_NESTED_MAPPING);
This code now outputs:
1 2 3 4 5
planets:
- name: Mercury
distance: 57910000
- name: Jupiter
distance: 778500000
Dumping Empty Entries
Consider the following code that dumps YAML data for a Docker Compose volumes section:
1 2
$data = ['volumes' => ['db-data' => null]];
$yaml = Yaml::dump($data);
This code outputs:
1 2
volumes:
db-data: null
If you use an empty string instead of null
as the value of db-data
,
you'll get this:
1 2
volumes:
db-data: ''
There is no way to dump this YAML entry as an empty entry without any content
(neither null
nor an empty string). That's why Symfony 7.3 introduced a new
flag to dump empty entries:
1 2
$data = ['volumes' => ['db-data' => null]];
$yaml = Yaml::dump($data, 2, 4, Yaml::DUMP_NULL_AS_EMPTY);
This code now outputs:
1 2
volumes:
db-data: