54133cffb0d3caf44c2147d6e72c8b833a74e015
[packbundle] / Twig / PackTokenParser.php
1 <?php
2 // src/Rapsys/PackBundle/Twig/PackTokenParser.php
3 namespace Rapsys\PackBundle\Twig;
4
5 use Symfony\Component\HttpKernel\Config\FileLocator;
6 use Symfony\Component\Asset\Packages;
7
8 class PackTokenParser extends \Twig_TokenParser {
9 private $tag;
10
11 /**
12 * Constructor.
13 *
14 * @param class $fileLocator The FileLocator instance
15 * @param class $assetsPackages The Assets Packages instance
16 * @param string $config The config path
17 * @param string $tag The tag name
18 * @param string $output The default output string
19 * @param array $filters The default filters array
20 */
21 public function __construct(FileLocator $fileLocator, Packages $assetsPackages, $config, $tag, $output, $filters) {
22 $this->fileLocator = $fileLocator;
23 $this->assetsPackages = $assetsPackages;
24
25 //Set prefix
26 $this->prefix = $config['prefix'];
27
28 //Set name
29 $this->name = $config['name'];
30
31 //Set scheme
32 $this->scheme = $config['scheme'];
33
34 //Set timeout
35 $this->timeout = $config['timeout'];
36
37 //Set agent
38 $this->agent = $config['agent'];
39
40 //Set redirect
41 $this->redirect = $config['redirect'];
42
43 //Set tag
44 $this->tag = $tag;
45
46 //Set output
47 $this->output = $output;
48
49 //Set filters
50 $this->filters = $filters;
51 }
52
53 public function getTag() {
54 return $this->tag;
55 }
56
57 public function parse(\Twig_Token $token) {
58 $parser = $this->parser;
59 $stream = $this->parser->getStream();
60
61 $inputs = array();
62 $name = $this->name;
63 $output = $this->output;
64 $filters = $this->filters;
65
66 $content = '';
67
68 while (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
69 if ($stream->test(\Twig_Token::STRING_TYPE)) {
70 // '@jquery', 'js/src/core/*', 'js/src/extra.js'
71 $inputs[] = $stream->next()->getValue();
72 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'filters')) {
73 // filter='yui_js'
74 $stream->next();
75 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
76 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(\Twig_Token::STRING_TYPE)->getValue()))));
77 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'output')) {
78 // output='js/packed/*.js' OR output='js/core.js'
79 $stream->next();
80 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
81 $output = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
82 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'name')) {
83 // name='core_js'
84 $stream->next();
85 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
86 $name = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
87 } else {
88 $token = $stream->getCurrent();
89 throw new \Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', \Twig_Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext());
90 }
91 }
92
93 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
94
95 $body = $this->parser->subparse(array($this, 'testEndTag'), true);
96
97 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
98
99 //Replace star with sha1
100 if (($pos = strpos($output, '*')) !== false) {
101 #XXX: assetic code: substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7)
102 $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 1);
103 }
104
105 //Deal with inputs
106 for($k = 0; $k < count($inputs); $k++) {
107 //Deal with generic url
108 if (strpos($inputs[$k], '//') === 0) {
109 //Fix url
110 $inputs[$k] = $this->scheme.substr($inputs[$k], 2);
111 //Deal with non url path
112 } elseif (strpos($inputs[$k], '://') === false) {
113 //Check if we have a bundle path
114 if ($inputs[$k][0] == '@') {
115 //Check that we don't have only a path
116 if (($pos = strpos($inputs[$k], '/')) === false) {
117 #TODO: @jquery support (if we really want it)
118 #header('Content-Type: text/plain');
119 #var_dump($inputs);
120 #if ($inputs[0] == '@jquery') {
121 # exit;
122 #}
123 throw new \Twig_Error_Syntax(sprintf('Invalid input path "%s"', $inputs[$k]), $token->getLine(), $stream->getSourceContext());
124 }
125 //Resolve bundle prefix
126 $inputs[$k] = $this->fileLocator->locate(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 1);
127 }
128 //Deal with globs
129 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
130 //Get replacement
131 $replacement = glob($inputs[$k], GLOB_NOSORT|GLOB_BRACE);
132 //Check that these are working files
133 foreach($replacement as $input) {
134 if (!is_file($input)) {
135 throw new \Twig_Error_Syntax(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext());
136 }
137 }
138 //Replace with glob path
139 array_splice($inputs, $k, 1, $replacement);
140 //Fix current key
141 $k += count($replacement) - 1;
142 //Check that it's a file
143 } elseif (!is_file($inputs[$k])) {
144 throw new \Twig_Error_Syntax(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext());
145 }
146 }
147 }
148
149 //Init context
150 $ctx = stream_context_create(
151 array(
152 'http' => array(
153 'timeout' => $this->timeout,
154 'user_agent' => $this->agent,
155 'redirect' => $this->redirect,
156 )
157 )
158 );
159
160 //Check inputs
161 if (!empty($inputs)) {
162 //Retrieve files content
163 foreach($inputs as $input) {
164 //Try to retrieve content
165 if (($data = file_get_contents($input, false, $ctx)) === false) {
166 throw new \Twig_Error_Syntax(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext());
167 }
168 //Append content
169 $content .= $data;
170 }
171 } else {
172 #TODO: trigger error about empty inputs ?
173 }
174
175 //Check filters
176 if (!empty($filters)) {
177 //Apply all filters
178 foreach($filters as $filter) {
179 //Init args
180 $args = array($stream->getSourceContext(), $token->getLine());
181 //Check if args is available
182 if (!empty($filter['args'])) {
183 //Append args if provided
184 $args += $filter['args'];
185 }
186 //Init reflection
187 $reflection = new \ReflectionClass($filter['class']);
188 //Set instance args
189 $tool = $reflection->newInstanceArgs($args);
190 //Process content
191 $content = $tool->process($content);
192 //Remove object
193 unset($tool, $reflection);
194 }
195 } else {
196 #TODO: trigger error about empty filters ?
197 }
198
199 //Create output dir on demand
200 if (!is_dir($parent = $dir = dirname($this->prefix.$output))) {
201 try {
202 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755)
203 mkdir($dir, 0777, true);
204 } catch (\Exception $e) {
205 throw new \Twig_Error_Syntax(sprintf('Unable to create directory: %s', $dir), $token->getLine(), $stream->getSourceContext());
206 }
207 }
208
209 //Send file content
210 //XXX: atomic rotation is required to avoid partial content in reverse cache
211 if (file_put_contents($this->prefix.$output.'.new', $content) === false) {
212 throw new \Twig_Error_Syntax(sprintf('Unable to write to: %s', $prefix.$output.'.new'), $token->getLine(), $stream->getSourceContext());
213 }
214
215 //Remove old file
216 if (is_file($this->prefix.$output) && unlink($this->prefix.$output) === false) {
217 throw new \Twig_Error_Syntax(sprintf('Unable to unlink: %s', $prefix.$output), $token->getLine(), $stream->getSourceContext());
218 }
219
220 //Rename it
221 if (rename($this->prefix.$output.'.new', $this->prefix.$output) === false) {
222 throw new \Twig_Error_Syntax(sprintf('Unable to rename: %s to %s', $prefix.$output.'.new', $prefix.$output), $token->getLine(), $stream->getSourceContext());
223 }
224
225 //Retrieve asset uri
226 //XXX: was next line to support module specific asset configuration
227 #if (($output = $this->assetsPackages->getUrl($output, 'rapsys_pack')) === false) {
228 if (($output = $this->assetsPackages->getUrl($output)) === false) {
229 #throw new \Twig_Error_Syntax(sprintf('Unable to get url for asset: %s with package %s', $output, 'rapsys_pack'), $token->getLine(), $stream->getSourceContext());
230 throw new \Twig_Error_Syntax(sprintf('Unable to get url for asset: %s', $output), $token->getLine(), $stream->getSourceContext());
231 }
232
233 //Send pack node
234 return new PackNode(array('value' => $body), array('inputs' => $inputs, 'filters' => $filters, 'name' => $name, 'output' => $output), $token->getLine(), $this->getTag());
235 }
236
237 public function testEndTag(\Twig_Token $token) {
238 return $token->test(array('end'.$this->getTag()));
239 }
240 }