Dev News Daily ENDE

Symfony 8.2 adds one-line Callback rules and precise BcMath comparisons to the Validator

Symfony 8.2 brings a set of changes to the Validator component, described by Javier Eguiluz in a post on the Symfony blog on 13 November, the same week the second beta of 8.2 was published.

The most visible change concerns the Callback constraint, the usual way to write a custom rule. It gains a message option. When the option is set, the callback only has to return a boolean, and Symfony creates the violation when it returns false. Combined with PHP 8.5, which allows static closures in constant expressions, the whole rule can live inside the attribute, for example a closure that checks that a delivery date lies in the future. The closure receives the same arguments as before, so it can still reach the object being validated through the execution context.

The Unique constraint's fields option, which checks uniqueness on only some fields of a collection, previously worked only for collections of arrays. In 8.2 it also works for collections of objects: public properties are read directly and other values through the PropertyAccess component, so getters and property paths work as well.

Financial code gets attention too. PHP 8.4 added BcMath\Number for arbitrary-precision arithmetic, and Range and the comparison constraints (EqualTo, NotEqualTo, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual) now accept such values. The post explains a trap this avoids: comparing a BcMath\Number with a float in PHP truncates the float to an integer, so new Number('10.2') > 10.5 is true. Symfony therefore converts the limits to BcMath\Number before comparing.

In custom validators, setParameter() previously accepted only strings while setParameters() accepted anything. It now takes strings, integers, floats, \Stringable and \DateTimeInterface, which matters when translations use the ICU message format to format numbers and dates. Group sequences can reference the class's own group with ::class instead of a short class name string, and a new cascadeCurrentGroup option makes objects marked with Valid be validated against the current group of the sequence, not only against Default. The groups option of Valid is also being reworked to separate when a nested object is validated from which of its constraints run.

Symfony 8.2 adds one-line Callback rules and precise BcMath comparisons to the Validator
Symfony 8.2 adds one-line Callback rules and precise BcMath comparisons to the Validator — Dev News Daily

Why it matters

The BcMath\Number change is the one that prevents silent errors. A validator that compares an exact decimal with a float limit could accept an amount just over the maximum, and nothing would report it. Applications that validate money with PHP 8.4's arbitrary-precision type get correct comparisons without having to know about the truncation rule.