3 namespace Drupal\Core\Template;
6 * A class that defines the Twig 'trans' token parser for Drupal.
8 * The token parser converts a token stream created from template source
9 * code into an Abstract Syntax Tree (AST). The AST will later be compiled
10 * into PHP code usable for runtime execution of the template.
12 * @see \Twig_TokenParser
13 * @see http://twig.sensiolabs.org/doc/extensions/i18n.html
14 * @see https://github.com/fabpot/Twig-extensions
16 class TwigTransTokenParser extends \Twig_TokenParser {
21 public function parse(\Twig_Token $token) {
22 $lineno = $token->getLine();
23 $stream = $this->parser->getStream();
29 if (!$stream->test(\Twig_Token::BLOCK_END_TYPE) && $stream->test(\Twig_Token::STRING_TYPE)) {
30 $body = $this->parser->getExpressionParser()->parseExpression();
32 if (!$stream->test(\Twig_Token::BLOCK_END_TYPE) && $stream->test(\Twig_Token::NAME_TYPE, 'with')) {
34 $options = $this->parser->getExpressionParser()->parseExpression();
37 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
38 $body = $this->parser->subparse([$this, 'decideForFork']);
39 if ('plural' === $stream->next()->getValue()) {
40 $count = $this->parser->getExpressionParser()->parseExpression();
41 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
42 $plural = $this->parser->subparse([$this, 'decideForEnd'], TRUE);
46 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
48 $this->checkTransString($body, $lineno);
50 $node = new TwigNodeTrans($body, $plural, $count, $options, $lineno, $this->getTag());
56 * Detect a 'plural' switch or the end of a 'trans' tag.
58 public function decideForFork($token) {
59 return $token->test(['plural', 'endtrans']);
63 * Detect the end of a 'trans' tag.
65 public function decideForEnd($token) {
66 return $token->test('endtrans');
72 public function getTag() {
77 * Ensure that any nodes that are parsed are only of allowed types.
79 * @param \Twig_Node $body
80 * The expression to check.
84 * @throws \Twig_Error_Syntax
86 protected function checkTransString(\Twig_Node $body, $lineno) {
87 foreach ($body as $node) {
89 $node instanceof \Twig_Node_Text
91 ($node instanceof \Twig_Node_Print && $node->getNode('expr') instanceof \Twig_Node_Expression_Name)
93 ($node instanceof \Twig_Node_Print && $node->getNode('expr') instanceof \Twig_Node_Expression_GetAttr)
95 ($node instanceof \Twig_Node_Print && $node->getNode('expr') instanceof \Twig_Node_Expression_Filter)
99 throw new \Twig_Error_Syntax(sprintf('The text to be translated with "trans" can only contain references to simple variables'), $lineno);