1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* Copyright 2011 Johannes M. Schmitt <[email protected]> |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
7
|
|
|
* you may not use this file except in compliance with the License. |
8
|
|
|
* You may obtain a copy of the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15
|
|
|
* See the License for the specific language governing permissions and |
16
|
|
|
* limitations under the License. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
namespace TwigJs\Compiler; |
20
|
|
|
|
21
|
|
|
use TwigJs\JsCompiler; |
22
|
|
|
use TwigJs\TypeCompilerInterface; |
23
|
|
|
|
24
|
|
|
class MacroCompiler implements TypeCompilerInterface |
25
|
|
|
{ |
26
|
|
|
public function getType() |
27
|
|
|
{ |
28
|
|
|
return 'Twig_Node_Macro'; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function compile(JsCompiler $compiler, \Twig_NodeInterface $node) |
32
|
|
|
{ |
33
|
|
|
if (!$node instanceof \Twig_Node_Macro) { |
34
|
|
|
throw new \RuntimeException( |
35
|
|
|
sprintf( |
36
|
|
|
'$node must be an instanceof of \Twig_Node_Macro, but got "%s".', |
37
|
|
|
get_class($node) |
38
|
|
|
) |
39
|
|
|
); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$compiler->enterScope(); |
43
|
|
|
|
44
|
|
|
$arguments = array(); |
45
|
|
|
foreach ($node->getNode('arguments') as $name => $argument) { |
46
|
|
|
if ($argument->hasAttribute('name')) { |
47
|
|
|
$name = $argument->getAttribute('name'); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$arguments[] = 'opt_'.$name; |
51
|
|
|
$compiler->setVar($name, 'opt_'.$name); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$compiler |
55
|
|
|
->addDebugInfo($node) |
56
|
|
|
->write("/**\n", " * Macro \"".$node->getAttribute('name')."\"\n", " *\n") |
57
|
|
|
; |
58
|
|
|
|
59
|
|
|
foreach ($arguments as $arg => $var) { |
60
|
|
|
$compiler->write(" * @param {*} $var\n"); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$compiler |
64
|
|
|
->write(" * @return {string}\n") |
65
|
|
|
->write(" */\n") |
66
|
|
|
->raw($compiler->templateFunctionName) |
67
|
|
|
->raw(".prototype.get") |
68
|
|
|
->raw($node->getAttribute('name')) |
69
|
|
|
->raw(" = function(".implode(', ', $arguments).") {\n") |
70
|
|
|
->indent() |
71
|
|
|
->write("var context = twig.extend({}, this.env_.getGlobals());\n\n") |
72
|
|
|
->write("var sb = new twig.StringBuffer;\n") |
73
|
|
|
->subcompile($node->getNode('body')) |
74
|
|
|
->raw("\n") |
75
|
|
|
->write("return new twig.Markup(sb.toString());\n") |
76
|
|
|
->outdent() |
77
|
|
|
->write("};\n\n") |
78
|
|
|
->leaveScope() |
79
|
|
|
; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|