Skip to content

[ExpressionLanguage] Add support for null-safe operator #45795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Symfony/Component/ExpressionLanguage/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ CHANGELOG
=========

6.1
-----
---

* Add support for null-safe syntax when parsing object's methods and properties
* Support lexing numbers with the numeric literal separator `_`
* Support lexing decimals with no leading zero

Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/ExpressionLanguage/Lexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ public function tokenize(string $expression): TokenStream
// operators
$tokens[] = new Token(Token::OPERATOR_TYPE, $match[0], $cursor + 1);
$cursor += \strlen($match[0]);
} elseif ('?' === $expression[$cursor] && '.' === ($expression[$cursor + 1] ?? '')) {
// null-safe
$tokens[] = new Token(Token::PUNCTUATION_TYPE, '?.', ++$cursor);
++$cursor;
} elseif (str_contains('.,?:', $expression[$cursor])) {
// punctuation
$tokens[] = new Token(Token::PUNCTUATION_TYPE, $expression[$cursor], $cursor + 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@
*/
class ConstantNode extends Node
{
public readonly bool $isNullSafe;
private bool $isIdentifier;

public function __construct(mixed $value, bool $isIdentifier = false)
public function __construct(mixed $value, bool $isIdentifier = false, bool $isNullSafe = false)
{
$this->isIdentifier = $isIdentifier;
$this->isNullSafe = $isNullSafe;
parent::__construct(
[],
['value' => $value]
Expand Down
11 changes: 9 additions & 2 deletions src/Symfony/Component/ExpressionLanguage/Node/GetAttrNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,20 @@ public function __construct(Node $node, Node $attribute, ArrayNode $arguments, i

public function compile(Compiler $compiler)
{
$nullSafe = $this->nodes['attribute'] instanceof ConstantNode && $this->nodes['attribute']->isNullSafe;
switch ($this->attributes['type']) {
case self::PROPERTY_CALL:
$compiler
->compile($this->nodes['node'])
->raw('->')
->raw($nullSafe ? '?->' : '->')
->raw($this->nodes['attribute']->attributes['value'])
;
break;

case self::METHOD_CALL:
$compiler
->compile($this->nodes['node'])
->raw('->')
->raw($nullSafe ? '?->' : '->')
->raw($this->nodes['attribute']->attributes['value'])
->raw('(')
->compile($this->nodes['arguments'])
Expand All @@ -69,6 +70,9 @@ public function evaluate(array $functions, array $values)
switch ($this->attributes['type']) {
case self::PROPERTY_CALL:
$obj = $this->nodes['node']->evaluate($functions, $values);
if (null === $obj && $this->nodes['attribute']->isNullSafe) {
return null;
}
if (!\is_object($obj)) {
throw new \RuntimeException(sprintf('Unable to get property "%s" of non-object "%s".', $this->nodes['attribute']->dump(), $this->nodes['node']->dump()));
}
Expand All @@ -79,6 +83,9 @@ public function evaluate(array $functions, array $values)

case self::METHOD_CALL:
$obj = $this->nodes['node']->evaluate($functions, $values);
if (null === $obj && $this->nodes['attribute']->isNullSafe) {
return null;
}
if (!\is_object($obj)) {
throw new \RuntimeException(sprintf('Unable to call method "%s" of non-object "%s".', $this->nodes['attribute']->dump(), $this->nodes['node']->dump()));
}
Expand Down
5 changes: 3 additions & 2 deletions src/Symfony/Component/ExpressionLanguage/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,8 @@ public function parsePostfixExpression(Node\Node $node)
{
$token = $this->stream->current;
while (Token::PUNCTUATION_TYPE == $token->type) {
if ('.' === $token->value) {
if ('.' === $token->value || '?.' === $token->value) {
$isNullSafe = '?.' === $token->value;
$this->stream->next();
$token = $this->stream->current;
$this->stream->next();
Expand All @@ -359,7 +360,7 @@ public function parsePostfixExpression(Node\Node $node)
throw new SyntaxError('Expected name.', $token->cursor, $this->stream->getExpression());
}

$arg = new Node\ConstantNode($token->value, true);
$arg = new Node\ConstantNode($token->value, true, $isNullSafe);

$arguments = new Node\ArgumentsNode();
if ($this->stream->current->test(Token::PUNCTUATION_TYPE, '(')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,12 +237,41 @@ public function testRegisterAfterEval($registerCallback)
$registerCallback($el);
}

public function testCallBadCallable()
/**
* @dataProvider provideNullSafe
*/
public function testNullSafeEvaluate($expression, $foo)
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessageMatches('/Unable to call method "\w+" of object "\w+"./');
$el = new ExpressionLanguage();
$el->evaluate('foo.myfunction()', ['foo' => new \stdClass()]);
$expressionLanguage = new ExpressionLanguage();
$this->assertNull($expressionLanguage->evaluate($expression, ['foo' => $foo]));
}

/**
* @dataProvider provideNullSafe
*/
public function testNullsafeCompile($expression, $foo)
{
$expressionLanguage = new ExpressionLanguage();
$this->assertNull(eval(sprintf('return %s;', $expressionLanguage->compile($expression, ['foo' => 'foo']))));
}

public function provideNullsafe()
{
$foo = new class() extends \stdClass {
public function bar()
{
return null;
}
};

yield ['foo?.bar', null];
yield ['foo?.bar()', null];
yield ['foo.bar?.baz', (object) ['bar' => null]];
yield ['foo.bar?.baz()', (object) ['bar' => null]];
yield ['foo["bar"]?.baz', ['bar' => null]];
yield ['foo["bar"]?.baz()', ['bar' => null]];
yield ['foo.bar()?.baz', $foo];
yield ['foo.bar()?.baz()', $foo];
}

/**
Expand Down
19 changes: 19 additions & 0 deletions src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,21 @@ public function getParseData()
new Node\BinaryNode('contains', new Node\ConstantNode('foo'), new Node\ConstantNode('f')),
'"foo" contains "f"',
],
[
new Node\GetAttrNode(new Node\NameNode('foo'), new Node\ConstantNode('bar', true, true), new Node\ArgumentsNode(), Node\GetAttrNode::PROPERTY_CALL),
'foo?.bar',
['foo'],
],
[
new Node\GetAttrNode(new Node\NameNode('foo'), new Node\ConstantNode('bar', true, true), new Node\ArgumentsNode(), Node\GetAttrNode::METHOD_CALL),
'foo?.bar()',
['foo'],
],
[
new Node\GetAttrNode(new Node\NameNode('foo'), new Node\ConstantNode('not', true, true), new Node\ArgumentsNode(), Node\GetAttrNode::METHOD_CALL),
'foo?.not()',
['foo'],
],

// chained calls
[
Expand Down Expand Up @@ -281,6 +296,10 @@ public function getLintData(): array
'expression' => 'foo["some_key"].callFunction(a ? b)',
'names' => ['foo', 'a', 'b'],
],
'valid expression with null safety' => [
'expression' => 'foo["some_key"]?.callFunction(a ? b)',
'names' => ['foo', 'a', 'b'],
],
'allow expression without names' => [
'expression' => 'foo.bar',
'names' => null,
Expand Down