mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-19 13:57:00 +00:00
Compile Elvis operator with Elvis operator
This commit is contained in:
@@ -183,11 +183,14 @@ class ExpressionParser
|
|||||||
if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
||||||
$expr2 = $this->parseExpression();
|
$expr2 = $this->parseExpression();
|
||||||
if ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
if ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
||||||
|
// Ternary operator (expr ? expr2 : expr3)
|
||||||
$expr3 = $this->parseExpression();
|
$expr3 = $this->parseExpression();
|
||||||
} else {
|
} else {
|
||||||
|
// Ternary without else (expr ? expr2)
|
||||||
$expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine());
|
$expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// Ternary without then (expr ?: expr3)
|
||||||
$expr2 = $expr;
|
$expr2 = $expr;
|
||||||
$expr3 = $this->parseExpression();
|
$expr3 = $this->parseExpression();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,14 +23,23 @@ class ConditionalExpression extends AbstractExpression
|
|||||||
|
|
||||||
public function compile(Compiler $compiler): void
|
public function compile(Compiler $compiler): void
|
||||||
{
|
{
|
||||||
$compiler
|
// Ternary with no then uses Elvis operator
|
||||||
->raw('((')
|
if ($this->getNode('expr1') === $this->getNode('expr2')) {
|
||||||
->subcompile($this->getNode('expr1'))
|
$compiler
|
||||||
->raw(') ? (')
|
->raw('((')
|
||||||
->subcompile($this->getNode('expr2'))
|
->subcompile($this->getNode('expr1'))
|
||||||
->raw(') : (')
|
->raw(') ?: (')
|
||||||
->subcompile($this->getNode('expr3'))
|
->subcompile($this->getNode('expr3'))
|
||||||
->raw('))')
|
->raw('))');
|
||||||
;
|
} else {
|
||||||
|
$compiler
|
||||||
|
->raw('((')
|
||||||
|
->subcompile($this->getNode('expr1'))
|
||||||
|
->raw(') ? (')
|
||||||
|
->subcompile($this->getNode('expr2'))
|
||||||
|
->raw(') : (')
|
||||||
|
->subcompile($this->getNode('expr3'))
|
||||||
|
->raw('))');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user