mirror of
https://github.com/twigphp/Twig.git
synced 2026-11-07 19:54:59 +00:00
Add the = assignment operator
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\ExpressionParser\Infix;
|
||||
|
||||
use Twig\Error\SyntaxError;
|
||||
use Twig\ExpressionParser\InfixAssociativity;
|
||||
use Twig\Node\Expression\AbstractExpression;
|
||||
use Twig\Node\Expression\Binary\AbstractBinary;
|
||||
use Twig\Node\Expression\Binary\SetBinary;
|
||||
use Twig\Node\Expression\Variable\ContextVariable;
|
||||
use Twig\Parser;
|
||||
use Twig\Token;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
class AssignmentExpressionParser extends BinaryOperatorExpressionParser
|
||||
{
|
||||
public function __construct(
|
||||
string $name,
|
||||
) {
|
||||
parent::__construct(SetBinary::class, $name, 0, InfixAssociativity::Right);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return AbstractBinary
|
||||
*/
|
||||
public function parse(Parser $parser, AbstractExpression $left, Token $token): AbstractExpression
|
||||
{
|
||||
if (!$left instanceof ContextVariable) {
|
||||
throw new SyntaxError(\sprintf('Cannot assign to "%s", only variables can be assigned.', $left::class), $token->getLine(), $parser->getStream()->getSourceContext());
|
||||
}
|
||||
$right = $parser->parseExpression(InfixAssociativity::Left === $this->getAssociativity() ? $this->getPrecedence() + 1 : $this->getPrecedence());
|
||||
$right = match ($this->getName()) {
|
||||
'=' => $right,
|
||||
default => throw new \LogicException(\sprintf('Unknown operator: %s.', $this->getName())),
|
||||
};
|
||||
|
||||
return new SetBinary($left, $right, $token->getLine());
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Assignment operator';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user