1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) 2010 Fabien Potencier
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12class Twig_Extensions_TokenParser_Trans extends Twig_TokenParser
13{
14    /**
15     * {@inheritdoc}
16     */
17    public function parse(Twig_Token $token)
18    {
19        $lineno = $token->getLine();
20        $stream = $this->parser->getStream();
21        $count = null;
22        $plural = null;
23        $notes = null;
24
25        if (!$stream->test(Twig_Token::BLOCK_END_TYPE)) {
26            $body = $this->parser->getExpressionParser()->parseExpression();
27        } else {
28            $stream->expect(Twig_Token::BLOCK_END_TYPE);
29            $body = $this->parser->subparse(array($this, 'decideForFork'));
30            $next = $stream->next()->getValue();
31
32            if ('plural' === $next) {
33                $count = $this->parser->getExpressionParser()->parseExpression();
34                $stream->expect(Twig_Token::BLOCK_END_TYPE);
35                $plural = $this->parser->subparse(array($this, 'decideForFork'));
36
37                if ('notes' === $stream->next()->getValue()) {
38                    $stream->expect(Twig_Token::BLOCK_END_TYPE);
39                    $notes = $this->parser->subparse(array($this, 'decideForEnd'), true);
40                }
41            } elseif ('notes' === $next) {
42                $stream->expect(Twig_Token::BLOCK_END_TYPE);
43                $notes = $this->parser->subparse(array($this, 'decideForEnd'), true);
44            }
45        }
46
47        $stream->expect(Twig_Token::BLOCK_END_TYPE);
48
49        $this->checkTransString($body, $lineno);
50
51        return new Twig_Extensions_Node_Trans($body, $plural, $count, $notes, $lineno, $this->getTag());
52    }
53
54    public function decideForFork(Twig_Token $token)
55    {
56        return $token->test(array('plural', 'notes', 'endtrans'));
57    }
58
59    public function decideForEnd(Twig_Token $token)
60    {
61        return $token->test('endtrans');
62    }
63
64    /**
65     * {@inheritdoc}
66     */
67    public function getTag()
68    {
69        return 'trans';
70    }
71
72    protected function checkTransString(Twig_Node $body, $lineno)
73    {
74        foreach ($body as $i => $node) {
75            if (
76                $node instanceof Twig_Node_Text
77                ||
78                ($node instanceof Twig_Node_Print && $node->getNode('expr') instanceof Twig_Node_Expression_Name)
79            ) {
80                continue;
81            }
82
83            throw new Twig_Error_Syntax(sprintf('The text to be translated with "trans" can only contain references to simple variables'), $lineno);
84        }
85    }
86}
87
88class_alias('Twig_Extensions_TokenParser_Trans', 'Twig\Extensions\TokenParser\TransTokenParser', false);
89