Skip to content

Commit

Permalink
[ExpressionLanguage] Fix null coalescing propagation
Browse files Browse the repository at this point in the history
  • Loading branch information
fancyweb committed Dec 9, 2023
1 parent 6d560c4 commit 1bea7c1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
15 changes: 14 additions & 1 deletion Node/NullCoalesceNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function compile(Compiler $compiler): void
public function evaluate(array $functions, array $values): mixed
{
if ($this->nodes['expr1'] instanceof GetAttrNode) {
$this->nodes['expr1']->attributes['is_null_coalesce'] = true;
$this->addNullCoalesceAttributeToGetAttrNodes($this->nodes['expr1']);
}

return $this->nodes['expr1']->evaluate($functions, $values) ?? $this->nodes['expr2']->evaluate($functions, $values);
Expand All @@ -49,4 +49,17 @@ public function toArray(): array
{
return ['(', $this->nodes['expr1'], ') ?? (', $this->nodes['expr2'], ')'];
}

private function addNullCoalesceAttributeToGetAttrNodes(Node $node): void
{
if (!$node instanceof GetAttrNode) {
return;
}

$node->attributes['is_null_coalesce'] = true;

foreach ($node->nodes as $node) {
$this->addNullCoalesceAttributeToGetAttrNodes($node);
}
}
}
3 changes: 3 additions & 0 deletions Tests/ExpressionLanguageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,9 @@ public function bar()
yield ['foo["bar"]["baz"] ?? "default"', ['bar' => null]];
yield ['foo["bar"].baz ?? "default"', ['bar' => null]];
yield ['foo.bar().baz ?? "default"', $foo];
yield ['foo.bar.baz.bam ?? "default"', (object) ['bar' => null]];
yield ['foo?.bar?.baz?.qux ?? "default"', (object) ['bar' => null]];
yield ['foo[123][456][789] ?? "default"', [123 => []]];
}

/**
Expand Down

0 comments on commit 1bea7c1

Please sign in to comment.