In addition to the main features announced in previous posts of this series, Symfony 8.2 includes many smaller changes that make day-to-day work easier. This post highlights the first batch.

Wildcards in Property Paths

Langning Zhang
Contributed by Langning Zhang in #65297

A property path of the PropertyAccess component reads a single branch of the data: each element selects one key or property. Getting the same field from all the items of a collection required a loop, and another one for each nesting level.

Symfony 8.2 adds the [*] path element, which means "all the elements at this level". It's disabled by default, so you must enable it explicitly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\PropertyAccess\PropertyAccess;

$accessor = PropertyAccess::createPropertyAccessorBuilder()
    ->enableWildcardReads()
    ->getPropertyAccessor();

$people = [
    ['name' => 'Ada', 'jobs' => [['title' => 'programmer'], ['title' => 'writer']]],
    ['name' => 'Grace', 'jobs' => [['title' => 'computer scientist']]],
];

$accessor->getValue($people, '[*][name]');
// ['Ada', 'Grace']

$accessor->getValue($people, '[*][jobs][*][title]');
// [['programmer', 'writer'], ['computer scientist']]

In Symfony applications, enable it with the framework.property_access.wildcard_reads option. Wildcards work on any iterable value (arrays, Doctrine collections, generators, etc.), each wildcard adds one nesting level to the result and the original keys are not preserved. They are only for reading: calling setValue() with a path that contains a wildcard throws an exception.

Converting the Case of Parts of a String

Nicolas Grekas
Contributed by Nicolas Grekas in #65842

The lower(), upper() and title() methods of the String component convert the whole string. Changing only some characters (e.g. what lcfirst() does) required your own code, and doing it right for all languages is hard.

In Symfony 8.2, these methods accept a regular expression that selects the parts of the string to convert:

1
2
3
4
5
6
7
8
9
10
11
12
use function Symfony\Component\String\u;

u('HELLO WORLD')->lower('/^./');        // 'hELLO WORLD'
u('hello world')->title(false, '/^./'); // 'Hello world'
u('hello world')->upper('/\b./');       // 'Hello World'

// which characters are "the first letter" depends on the language;
// in Dutch, the "ij" digraph is capitalized as a whole
u('ijsland')->upper('/^ij|^./');        // 'IJsland'

// the locale-aware methods accept the same argument
u('ISTANBUL')->localeLower('tr', '/^./'); // 'ıSTANBUL'

All the matches are converted, so anchor the pattern (e.g. with ^) when you want to change only one part. The pattern follows the same rules as in the replaceMatches() method.

Boundaries of Time-Ordered UUIDs and ULIDs

Emanuele Panzeri
Contributed by Emanuele Panzeri in #63941

ULIDs and UUIDs v6 and v7 are sorted by their creation time. That's why you can find the rows created in a period of time using only the primary key, without adding and indexing a createdAt column. The missing piece was getting the lowest and highest possible IDs for a given moment.

Symfony 8.2 adds a createBoundaries() method to the Ulid, UuidV6 and UuidV7 classes. It returns those two IDs for the given time (or for the current time if you don't pass any):

1
2
3
4
5
6
7
8
9
10
11
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\Uid\UuidV7;

[$min] = UuidV7::createBoundaries(new \DateTimeImmutable('2026-11-01 00:00:00'));
[, $max] = UuidV7::createBoundaries(new \DateTimeImmutable('2026-11-30 23:59:59.999'));

$novemberOrders = $entityManager
    ->createQuery('SELECT o FROM App\Entity\Order o WHERE o.id BETWEEN :min AND :max')
    ->setParameter('min', $min, UuidType::NAME)
    ->setParameter('max', $max, UuidType::NAME)
    ->getResult();

The boundaries cover the time resolution of each type: one millisecond for ULIDs and UUIDs v7, and 100 nanoseconds for UUIDs v6. These three classes implement the new TimeOrderedUidInterface. UuidV1 doesn't implement it because, although it stores a date, its bytes are not sorted by time.

Excluding Directories Only at the Root

Josh
Contributed by Josh in #54752

The exclude() method of the Finder component excludes the directories with the given name at any depth. This is a problem when you only want to skip a top-level directory, because other directories with the same name deeper in the tree are skipped too.

In Symfony 8.2, a leading / anchors the path to the directory passed to in(), the same as .gitignore files do:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Finder\Finder;

// excludes all "data" directories: <project>/data/, <project>/src/Import/data/, etc.
$finder = (new Finder())->files()->in($projectDir)->exclude('data');

// excludes <project>/data/ but keeps <project>/src/Import/data/
$finder = (new Finder())->files()->in($projectDir)->exclude('/data');

// excludes only <project>/assets/vendor/
$finder = (new Finder())->files()->in($projectDir)->exclude('/assets/vendor');

Paths without the leading slash work as before.

Selecting Form Options by Their Text

Michaël Thieulin
Contributed by Michaël Thieulin in #64154

When filling a <select> field in a functional test, you had to pass the internal value of the option (e.g. an entity ID) instead of the text that users see in the browser. Symfony 8.2 adds a selectByText() method to the DomCrawler component for that:

1
2
3
4
5
6
7
8
9
10
11
$crawler = $client->request('GET', '/orders/new');
$form = $crawler->selectButton('Save')->form();

// before, you had to know the value of the option
$form['order[country]']->select('GB');

// now, you can use the text that users see
$form['order[country]']->selectByText('United Kingdom');

// in <select multiple> fields, pass an array to select many options
$form['order[labels]']->selectByText(['Gift', 'Fragile']);

The comparison is case-sensitive and ignores leading, trailing and repeated white spaces, the same as Crawler::text(). If no option matches, the exception message lists all the available texts.

A count() Function in Expressions

Payene Denis KOMBATE
Contributed by Payene Denis KOMBATE in #64870

The ExpressionLanguage component didn't provide a way to count the elements of a collection, so you had to register a custom function or pass the count as a variable. Symfony 8.2 adds a count() function that works the same as the PHP function with the same name:

1
2
3
4
5
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

$expressionLanguage = new ExpressionLanguage();

$expressionLanguage->evaluate('count(order.getItems()) > 10', ['order' => $order]);

A normalize Twig Filter

Ousama Ben Younes
Contributed by Ousama Ben Younes in #65040

The serialize Twig filter returns a string (e.g. JSON). That's a problem when you pass the result to something that encodes its own arguments, like the props of a Symfony UX component, because you end up with a JSON string inside JSON.

Symfony 8.2 adds a normalize filter that uses the Serializer component to return the normalized data (arrays and scalars) instead of a string:

1
2
3
4
5
6
7
{# the "product" prop is an array, not a JSON string #}
<div {{ vue_component('ProductCard', {product: product|normalize}) }}></div>

{# like "serialize", it accepts a format and a context #}
<div {{ vue_component('ProductCard', {
    product: product|normalize('json', {groups: ['product:read']})
}) }}></div>

More YAML Core Tags

Alexander Dmitryuk
Contributed by Alexander Dmitryuk in #65243

The YAML specification defines some tags to set the type of a value explicitly. The Yaml component supported !!str, !!float and !!binary. Symfony 8.2 adds support for !!int, !!bool and !!null. These three tags and !!float also accept quoted values:

1
2
3
4
5
port: !!int "8080"      # 8080 (integer)
mode: !!int 0o644       # 420 (integer)
ratio: !!float "1.5"    # 1.5 (float)
debug: !!bool "true"    # true (boolean)
fallback: !!null ~      # null

These tags are strict and follow the YAML 1.2 core schema. A value that is not valid for its tag (e.g. !!bool yes or !!int 1.5) throws a ParseException. This also applies to !!float, which before converted invalid values to 0.0.

Processes That Inherit the Standard Streams

Grégoire Pineau
Contributed by Grégoire Pineau in #66949

The Process component can read the output of a command through pipes, run it in a PTY or connect it to the terminal (TTY mode). None of them does what a shell script does: let the command use the same input, output and error streams of the current process. The TTY mode is the closest one, but it ignores redirections like php script.php 2> errors.log and fails when there's no terminal, as happens in some CI services.

Symfony 8.2 adds an inheritStdio() method for that:

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

$process = new Process(['docker', 'compose', 'run', '--rm', 'php', 'vendor/bin/phpunit']);
$process->inheritStdio();

// colors and interactivity in a terminal, plain output when redirected
// to a file or piped to another command
$exitCode = $process->run();

The output goes straight to the streams of the current process, so it's not captured: getOutput() returns an empty string and callbacks are not called. This mode can't be combined with the TTY mode or with an idle timeout.

Scheduling Tasks Only in Some Environments

Louis-Arnaud
Contributed by Louis-Arnaud in #64665

Some tasks must only be scheduled in certain environments (e.g. sending a report in production but not in staging). When using the attributes of the Scheduler component, there was no way to define this.

In Symfony 8.2, the #[AsCronTask] and #[AsPeriodicTask] attributes have a new env option to set one or more environments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/Command/SendWeeklyReportCommand.php
namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Scheduler\Attribute\AsCronTask;

#[AsCommand(name: 'app:send-weekly-report')]
#[AsCronTask('0 8 * * 1', env: 'prod')]
// use an array for several environments:
// #[AsCronTask('0 8 * * 1', env: ['prod', 'staging'])]
class SendWeeklyReportCommand
{
    public function __invoke(): int
    {
        // ...

        return Command::SUCCESS;
    }
}

In the other environments the task is not added to the schedule, but the schedule still exists, so you can run the same workers everywhere.

Stateful Schedules via Configuration

Nicolas Grekas
Contributed by Nicolas Grekas in #66670

The schedules created with the #[AsCronTask] and #[AsPeriodicTask] attributes are stateless. If a worker stops in the middle of a run (e.g. because of --time-limit), the pending messages of that run are lost. Making them stateful required creating a schedule provider just to call stateful() and lock().

Symfony 8.2 adds a schedules option to configure each schedule by its name:

1
2
3
4
# config/packages/scheduler.yaml
scheduler:
    schedules:
        default: { stateful: true }

A stateful schedule stores its state in the cache.scheduler pool and, when the Lock component is enabled, it's also locked so only one worker runs it at the same time. Use the cache_pool and lock_factory options to select other services, and process_only_last_missed_run to run a task once after some downtime instead of once per missed run. These options also work for the schedules created with a schedule provider.

Removing the Data of Unused Locales

Nicolas Grekas
Contributed by Nicolas Grekas in #67532

The Intl component includes the data (names of languages, countries, currencies, etc.) of all the locales, which takes around 8 MB. Most applications only use a few of them, so Symfony 8.2 adds a prune script to remove the data of all the locales except the ones that you pass to it:

1
$ php vendor/symfony/intl/Resources/bin/prune fr de

The script also keeps the regional variants of the given locales (e.g. fr_CA for fr), the parent locales that they need and English, which is the fallback of all locales. The removed locales behave like unknown ones and display the names in English.

In this example, the data goes from 8 MB to 300 KB (or 216 KB if you also run the existing compress script).

Published in #Living on the edge