aboutsummaryrefslogtreecommitdiffhomepage
path: root/inc/Twig/TokenParser/Set.php
diff options
context:
space:
mode:
Diffstat (limited to 'inc/Twig/TokenParser/Set.php')
-rw-r--r--inc/Twig/TokenParser/Set.php84
1 files changed, 84 insertions, 0 deletions
diff --git a/inc/Twig/TokenParser/Set.php b/inc/Twig/TokenParser/Set.php
new file mode 100644
index 00000000..70e0b41b
--- /dev/null
+++ b/inc/Twig/TokenParser/Set.php
@@ -0,0 +1,84 @@
1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) 2009 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
12/**
13 * Defines a variable.
14 *
15 * <pre>
16 * {% set foo = 'foo' %}
17 *
18 * {% set foo = [1, 2] %}
19 *
20 * {% set foo = {'foo': 'bar'} %}
21 *
22 * {% set foo = 'foo' ~ 'bar' %}
23 *
24 * {% set foo, bar = 'foo', 'bar' %}
25 *
26 * {% set foo %}Some content{% endset %}
27 * </pre>
28 */
29class Twig_TokenParser_Set extends Twig_TokenParser
30{
31 /**
32 * Parses a token and returns a node.
33 *
34 * @param Twig_Token $token A Twig_Token instance
35 *
36 * @return Twig_NodeInterface A Twig_NodeInterface instance
37 */
38 public function parse(Twig_Token $token)
39 {
40 $lineno = $token->getLine();
41 $stream = $this->parser->getStream();
42 $names = $this->parser->getExpressionParser()->parseAssignmentExpression();
43
44 $capture = false;
45 if ($stream->test(Twig_Token::OPERATOR_TYPE, '=')) {
46 $stream->next();
47 $values = $this->parser->getExpressionParser()->parseMultitargetExpression();
48
49 $stream->expect(Twig_Token::BLOCK_END_TYPE);
50
51 if (count($names) !== count($values)) {
52 throw new Twig_Error_Syntax("When using set, you must have the same number of variables and assignments.", $stream->getCurrent()->getLine(), $stream->getFilename());
53 }
54 } else {
55 $capture = true;
56
57 if (count($names) > 1) {
58 throw new Twig_Error_Syntax("When using set with a block, you cannot have a multi-target.", $stream->getCurrent()->getLine(), $stream->getFilename());
59 }
60
61 $stream->expect(Twig_Token::BLOCK_END_TYPE);
62
63 $values = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
64 $stream->expect(Twig_Token::BLOCK_END_TYPE);
65 }
66
67 return new Twig_Node_Set($capture, $names, $values, $lineno, $this->getTag());
68 }
69
70 public function decideBlockEnd(Twig_Token $token)
71 {
72 return $token->test('endset');
73 }
74
75 /**
76 * Gets the tag name associated with this token parser.
77 *
78 * @return string The tag name
79 */
80 public function getTag()
81 {
82 return 'set';
83 }
84}