]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/PackTokenParser.php
Update documentation
[packbundle] / Twig / PackTokenParser.php
1 <?php
2
3 namespace Rapsys\PackBundle\Twig;
4
5 use Symfony\Component\HttpKernel\Config\FileLocator;
6 use Symfony\Component\Asset\PackageInterface;
7 use Twig\Error\Error;
8 use Twig\Node\Expression\AssignNameExpression;
9 use Twig\Node\Node;
10 use Twig\Node\SetNode;
11 use Twig\Node\TextNode;
12 use Twig\Source;
13 use Twig\Token;
14 use Twig\TokenParser\AbstractTokenParser;
15
16 class PackTokenParser extends AbstractTokenParser {
17 ///The tag name
18 protected $tag;
19
20 /**
21 * Constructor
22 *
23 * @param FileLocator locator The FileLocator instance
24 * @param PackageInterface package The Assets Package instance
25 * @param array config The config path
26 * @param string tag The tag name
27 * @param string output The default output string
28 * @param array filters The default filters array
29 */
30 public function __construct(FileLocator $locator, PackageInterface $package, $config, $tag, $output, $filters) {
31 //Save locator
32 $this->locator = $locator;
33
34 //Save assets package
35 $this->package = $package;
36
37 //Set name
38 $this->name = $config['name'];
39
40 //Set scheme
41 $this->scheme = $config['scheme'];
42
43 //Set timeout
44 $this->timeout = $config['timeout'];
45
46 //Set agent
47 $this->agent = $config['agent'];
48
49 //Set redirect
50 $this->redirect = $config['redirect'];
51
52 //Set tag
53 $this->tag = $tag;
54
55 //Set output
56 $this->output = $output;
57
58 //Set filters
59 $this->filters = $filters;
60 }
61
62 /**
63 * Get the tag name
64 *
65 * @return string This tag name
66 */
67 public function getTag() {
68 return $this->tag;
69 }
70
71 /**
72 * Parse the token
73 *
74 * @param Token token The \Twig\Token instance
75 *
76 * @return Node The PackNode
77 *
78 * @todo see if we can't add a debug mode behaviour
79 *
80 * If twig.debug or env=dev (or rapsys_pack.config.debug?) is set, it should be possible to loop on each input
81 * and process the captured body without applying requested filter.
82 *
83 * @todo list:
84 * - detect debug mode
85 * - retrieve fixe link from input s%@(Name)Bundle/Resources/public(/somewhere/file.ext)%/bundles/\L\1\E\2%
86 * - for each inputs:
87 * - generate a set asset_url=x
88 * - generate a body
89 */
90 public function parse(Token $token) {
91 $parser = $this->parser;
92 $stream = $this->parser->getStream();
93
94 $inputs = [];
95 $name = $this->name;
96 $output = $this->output;
97 $filters = $this->filters;
98
99 $content = '';
100
101 //Process the token block until end
102 while (!$stream->test(Token::BLOCK_END_TYPE)) {
103 //The files to process
104 if ($stream->test(Token::STRING_TYPE)) {
105 //'somewhere/somefile.(css,img,js)' 'somewhere/*' '@jquery'
106 $inputs[] = $stream->next()->getValue();
107 //The filters token
108 } elseif ($stream->test(Token::NAME_TYPE, 'filters')) {
109 //filter='yui_js'
110 $stream->next();
111 $stream->expect(Token::OPERATOR_TYPE, '=');
112 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(Token::STRING_TYPE)->getValue()))));
113 //The output token
114 } elseif ($stream->test(Token::NAME_TYPE, 'output')) {
115 //output='js/packed/*.js' OR output='js/core.js'
116 $stream->next();
117 $stream->expect(Token::OPERATOR_TYPE, '=');
118 $output = $stream->expect(Token::STRING_TYPE)->getValue();
119 //The name token
120 } elseif ($stream->test(Token::NAME_TYPE, 'name')) {
121 //name='core_js'
122 $stream->next();
123 $stream->expect(Token::OPERATOR_TYPE, '=');
124 $name = $stream->expect(Token::STRING_TYPE)->getValue();
125 //Unexpected token
126 } else {
127 $token = $stream->getCurrent();
128 throw new Error(sprintf('Unexpected token "%s" of value "%s"', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext());
129 }
130 }
131
132 //Process end block
133 $stream->expect(Token::BLOCK_END_TYPE);
134
135 //Process body
136 $body = $this->parser->subparse([$this, 'testEndTag'], true);
137
138 //Process end block
139 $stream->expect(Token::BLOCK_END_TYPE);
140
141 //TODO: debug mode should be inserted here before the output variable is rewritten
142
143 //Replace star with sha1
144 if (($pos = strpos($output, '*')) !== false) {
145 //XXX: assetic use substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7)
146 $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 1);
147 }
148
149 //Process inputs
150 for($k = 0; $k < count($inputs); $k++) {
151 //Deal with generic url
152 if (strpos($inputs[$k], '//') === 0) {
153 //Fix url
154 $inputs[$k] = $this->scheme.substr($inputs[$k], 2);
155 //Deal with non url path
156 } elseif (strpos($inputs[$k], '://') === false) {
157 //Check if we have a bundle path
158 if ($inputs[$k][0] == '@') {
159 //Resolve it
160 $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext());
161 }
162
163 //Deal with globs
164 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
165 //Get replacement
166 $replacement = glob($inputs[$k], GLOB_NOSORT|GLOB_BRACE);
167 //Check that these are working files
168 foreach($replacement as $input) {
169 //Check that it's a file
170 if (!is_file($input)) {
171 throw new Error(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext());
172 }
173 }
174 //Replace with glob path
175 array_splice($inputs, $k, 1, $replacement);
176 //Fix current key
177 $k += count($replacement) - 1;
178 //Check that it's a file
179 } elseif (!is_file($inputs[$k])) {
180 throw new Error(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext());
181 }
182 }
183 }
184
185 //Init context
186 $ctx = stream_context_create(
187 [
188 'http' => [
189 'timeout' => $this->timeout,
190 'user_agent' => $this->agent,
191 'redirect' => $this->redirect,
192 ]
193 ]
194 );
195
196 //Check inputs
197 if (!empty($inputs)) {
198 //Retrieve files content
199 foreach($inputs as $input) {
200 //Try to retrieve content
201 if (($data = file_get_contents($input, false, $ctx)) === false) {
202 throw new Error(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext());
203 }
204 //Append content
205 $content .= $data;
206 }
207 } else {
208 //Trigger error about empty inputs ?
209 //XXX: There may be a legitimate case where we want an empty file or an error, feel free to contact the author in such case
210 #throw new Error('Empty inputs token', $token->getLine(), $stream->getSourceContext());
211
212 //Send an empty node without inputs
213 return new Node();
214 }
215
216 //Check filters
217 if (!empty($filters)) {
218 //Apply all filters
219 foreach($filters as $filter) {
220 //Init args
221 $args = [$stream->getSourceContext(), $token->getLine()];
222 //Check if args is available
223 if (!empty($filter['args'])) {
224 //Append args if provided
225 $args += $filter['args'];
226 }
227 //Init reflection
228 $reflection = new \ReflectionClass($filter['class']);
229 //Set instance args
230 $tool = $reflection->newInstanceArgs($args);
231 //Process content
232 $content = $tool->process($content);
233 //Remove object
234 unset($tool, $reflection);
235 }
236 } else {
237 //Trigger error about empty filters ?
238 //XXX: There may be a legitimate case where we want only a merged file or an error, feel free to contact the author in such case
239 #throw new Error('Empty filters token', $token->getLine(), $stream->getSourceContext());
240 }
241
242 //Retrieve asset uri
243 //XXX: this path is the merge of services.assets.path_package.arguments[0] and rapsys_pack.output.(css,img,js)
244 if (($outputUrl = $this->package->getUrl($output)) === false) {
245 throw new Error(sprintf('Unable to get url for asset: %s', $output), $token->getLine(), $stream->getSourceContext());
246 }
247
248 //Check if we have a bundle path
249 if ($output[0] == '@') {
250 //Resolve it
251 $output = $this->getLocated($output, $token->getLine(), $stream->getSourceContext());
252 }
253
254 //Create output dir if not present
255 if (!is_dir($dir = dirname($output))) {
256 try {
257 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755)
258 if (mkdir($dir, 0777, true) === false) {
259 throw new \Exception();
260 }
261 } catch (\Exception $e) {
262 throw new Error(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext(), $e);
263 }
264 }
265
266 //Send file content
267 //XXX: to avoid partial content in reverse cache we use atomic rotation write, unlink and move
268 try {
269 if (file_put_contents($output.'.new', $content) === false) {
270 throw new \Exception();
271 }
272 } catch(\Exception $e) {
273 throw new Error(sprintf('Unable to write to: %s', $output.'.new'), $token->getLine(), $stream->getSourceContext(), $e);
274 }
275
276 //Remove old file
277 if (is_file($output)) {
278 try {
279 if (unlink($output) === false) {
280 throw new \Exception();
281 }
282 } catch (\Exception $e) {
283 throw new Error(sprintf('Unable to unlink: %s', $output), $token->getLine(), $stream->getSourceContext(), $e);
284 }
285 }
286
287 //Rename it
288 try {
289 if (rename($output.'.new', $output) === false) {
290 throw new \Exception();
291 }
292 } catch (\Exception $e) {
293 throw new Error(sprintf('Unable to rename: %s to %s', $output.'.new', $output), $token->getLine(), $stream->getSourceContext(), $e);
294 }
295
296 //Set name in context key
297 $ref = new AssignNameExpression($name, $token->getLine());
298
299 //Set output in context value
300 $value = new TextNode($outputUrl, $token->getLine());
301
302 //Send body with context set
303 return new Node([
304 //This define name in twig template by prepending $context['<name>'] = '<output>';
305 new SetNode(true, $ref, $value, $token->getLine(), $this->getTag()),
306 //The tag captured body
307 $body
308 ]);
309 }
310
311 /**
312 * Test for tag end
313 *
314 * @param Token token The \Twig\Token instance
315 *
316 * @return bool
317 */
318 public function testEndTag(Token $token) {
319 return $token->test(['end'.$this->getTag()]);
320 }
321
322 /**
323 * Get path from bundled file
324 *
325 * @param string file The bundled file path
326 * @param int lineno The template line where the error occurred
327 * @param Source source The source context where the error occurred
328 * @param \Exception prev The previous exception
329 *
330 * @return string The resolved file path
331 */
332 public function getLocated($file, int $lineno = 0, Source $source = null, \Exception $prev = null) {
333 /*TODO: add a @jquery magic feature ?
334 if ($file == '@jquery') {
335 #header('Content-Type: text/plain');
336 #var_dump($inputs);
337 #exit;
338 return $this->config['jquery'];
339 }*/
340
341 //Check that we have a / separator between bundle name and path
342 if (($pos = strpos($file, '/')) === false) {
343 throw new Error(sprintf('Invalid path "%s"', $file), $token->getLine(), $stream->getSourceContext());
344 }
345
346 //Set bundle
347 $bundle = substr($file, 0, $pos);
348
349 //Set path
350 $path = substr($file, $pos + 1);
351
352 //Check for bundle suffix presence
353 //XXX: use "bundle templates automatic namespace" mimicked behaviour to find intended bundle and/or path
354 //XXX: see https://symfony.com/doc/4.3/templates.html#bundle-templates
355 if (strlen($bundle) < strlen('Bundle') || substr($bundle, -strlen('Bundle')) !== 'Bundle') {
356 //Append Bundle in an attempt to fix it's naming for locator
357 $bundle .= 'Bundle';
358
359 //Check for public resource prefix presence
360 if (strlen($path) < strlen('Resources/public') || substr($path, 0, strlen('Resources/public')) != 'Resources/public') {
361 //Prepend standard public path
362 $path = 'Resources/public/'.$path;
363 }
364 }
365
366 //Resolve bundle prefix
367 try {
368 $prefix = $this->locator->locate($bundle);
369 //Catch bundle does not exist or is not enabled exception
370 } catch(\InvalidArgumentException $e) {
371 //Fix lowercase first bundle character
372 if ($bundle[1] > 'Z' || $bundle[1] < 'A') {
373 $bundle[1] = strtoupper($bundle[1]);
374 }
375
376 //Detect double bundle suffix
377 if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') {
378 //Strip extra bundle
379 $bundle = substr($bundle, 0, -strlen('Bundle'));
380 }
381
382 //Convert snake case in camel case
383 if (strpos($bundle, '_') !== false) {
384 //Fix every first character following a _
385 while(($cur = strpos($bundle, '_')) !== false) {
386 $bundle = substr($bundle, 0, $cur).ucfirst(substr($bundle, $cur + 1));
387 }
388 }
389
390 //Resolve fixed bundle prefix
391 try {
392 $prefix = $this->locator->locate($bundle);
393 //Catch bundle does not exist or is not enabled exception again
394 } catch(\InvalidArgumentException $e) {
395 //Bail out as bundle or path is invalid and we have no way to know what was meant
396 throw new Error(sprintf('Invalid bundle name "%s" in path "%s". Maybe you meant "%s"', substr($file, 1, $pos - 1), $file, $bundle.'/'.$path), $token->getLine(), $stream->getSourceContext(), $e);
397 }
398 }
399
400 //Return solved bundle prefix and path
401 return $prefix.$path;
402 }
403 }