]>
Commit | Line | Data |
---|---|---|
a4565e88 NL |
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 | class Twig_Extensions_TokenParser_Trans extends Twig_TokenParser | |
12 | { | |
13 | /** | |
14 | * Parses a token and returns a node. | |
15 | * | |
16 | * @param Twig_Token $token A Twig_Token instance | |
17 | * | |
18 | * @return Twig_NodeInterface A Twig_NodeInterface instance | |
19 | */ | |
20 | public function parse(Twig_Token $token) | |
21 | { | |
22 | $lineno = $token->getLine(); | |
23 | $stream = $this->parser->getStream(); | |
24 | $count = null; | |
25 | $plural = null; | |
26 | ||
27 | if (!$stream->test(Twig_Token::BLOCK_END_TYPE)) { | |
28 | $body = $this->parser->getExpressionParser()->parseExpression(); | |
29 | } else { | |
30 | $stream->expect(Twig_Token::BLOCK_END_TYPE); | |
31 | $body = $this->parser->subparse(array($this, 'decideForFork')); | |
32 | if ('plural' === $stream->next()->getValue()) { | |
33 | $count = $this->parser->getExpressionParser()->parseExpression(); | |
34 | $stream->expect(Twig_Token::BLOCK_END_TYPE); | |
35 | $plural = $this->parser->subparse(array($this, 'decideForEnd'), true); | |
36 | } | |
37 | } | |
38 | ||
39 | $stream->expect(Twig_Token::BLOCK_END_TYPE); | |
40 | ||
41 | $this->checkTransString($body, $lineno); | |
42 | ||
43 | return new Twig_Extensions_Node_Trans($body, $plural, $count, $lineno, $this->getTag()); | |
44 | } | |
45 | ||
46 | public function decideForFork(Twig_Token $token) | |
47 | { | |
48 | return $token->test(array('plural', 'endtrans')); | |
49 | } | |
50 | ||
51 | public function decideForEnd(Twig_Token $token) | |
52 | { | |
53 | return $token->test('endtrans'); | |
54 | } | |
55 | ||
56 | /** | |
57 | * Gets the tag name associated with this token parser. | |
58 | * | |
59 | * @param string The tag name | |
60 | */ | |
61 | public function getTag() | |
62 | { | |
63 | return 'trans'; | |
64 | } | |
65 | ||
66 | protected function checkTransString(Twig_NodeInterface $body, $lineno) | |
67 | { | |
68 | foreach ($body as $i => $node) { | |
69 | if ( | |
70 | $node instanceof Twig_Node_Text | |
71 | || | |
72 | ($node instanceof Twig_Node_Print && $node->getNode('expr') instanceof Twig_Node_Expression_Name) | |
73 | ) { | |
74 | continue; | |
75 | } | |
76 | ||
77 | throw new Twig_Error_Syntax(sprintf('The text to be translated with "trans" can only contain references to simple variables'), $lineno); | |
78 | } | |
79 | } | |
80 | } |