Symfony 8.2 New Published on

Reading a whole collection with [*]

A path like [*][members][*][email] replaces nested loops: PropertyAccess reads every element of a collection.

Topics covered: PropertyAccess

New in Symfony 8.2 (in development). A PropertyAccess path reads a single branch: [0][name], [members][1][email]. To read the same field in every element of a collection, you needed a loop, and one more loop per nesting level. Symfony 8.2 adds the [*] wildcard, which stands for all the elements.

Before

$emails = [];
foreach ($teams as $team) {
    $emails[] = array_map(fn (array $member) => $member['email'], $team['members']);
}

Since Symfony 8.2

$emails = $accessor->getValue($teams, '[*][members][*][email]');
// [['ada@…', 'linus@…'], ['grace@…']]

Each [*] adds a level to the result, and the keys are replaced by a list. The wildcard is disabled by default. In an application, you enable it through configuration:

property_access:
    wildcard_reads: true

Your task

Enable the wildcard in config/packages/property_access.yaml. Then rewrite the two methods of Extracteur with the application's accessor (PropertyAccessorInterface), without loops or array_map. The results must not change: the /report preview displays them.

Where the feature comes from: the original pull request.