The ExpressionLanguage component provides an engine that can compile and evaluate expressions. The main purpose of this component is to use expressions inside configuration for more complex logic. Its other purpose is to use it to build business rule engines.
In Symfony 6.1 we're improving the already rich ExpressionLanguage syntax with more features.
New Syntax Options for Numbers
In order to better align with the expressions supported in modern PHP code, you can now define numbers using the following syntax:
1 2 3 4 5 6 7
# you can remove the leading zero of decimal numbers (in previous versions you had to use 0.99)
$expressionLanguage->evaluate('product.price <= .99', ['...' => '...'])
# all numbers support optional underscores as separators to improve readability
# (underscores are removed before evaluating the expressions)
$expressionLanguage->evaluate('product.stock > 1_000_000', ['...' => '...'])
$expressionLanguage->evaluate('2 * 3.14159_26535 * radius', ['...' => '...'])
New Operators
First, we've added a new ?.
operator which is equivalent to the PHP
null-safe operator. It prevents errors when trying to access a property or
method of an object that is null:
1 2 3 4 5
// this will throw an exception when `fruit` is `null`
$expressionLanguage->evaluate('fruit.color', ['fruit' => '...'])
// this will return `null` if `fruit` is `null`
$expressionLanguage->evaluate('fruit?.color', ['fruit' => '...'])
In addition to the null-safe operator, we've added three new operators (contains
,
starts with
and ends with
) that allow to create very readable expressions:
1 2 3
$expressionLanguage->evaluate('coupon.code starts with "XXX"', ['...' => '...'])
$expressionLanguage->evaluate('imported_file.path ends with ".csv"', ['...' => '...'])
$expressionLanguage->evaluate('url contains "example.com"', ['...' => '...'])
These operators were already available in Twig templates, making ExpressionLanguage component more in sync with Twig.
Hello !
Small typo in the code snippet below:
it should be starts instead of stars ;)
Hugo, thanks for reporting this typo. We've just fixed it. Cheers!
Nice! But would it be possible to use underscores also in operators? Might make them more readable when they span several words:
'imported_file.path ends_with ".csv"'