3 namespace Rapsys\PackBundle\Twig
;
5 use Symfony\Component\HttpKernel\Config\FileLocator
;
6 use Symfony\Component\Asset\PackageInterface
;
8 use Twig\Node\Expression\AssignNameExpression
;
10 use Twig\Node\SetNode
;
11 use Twig\Node\TextNode
;
14 use Twig\TokenParser\AbstractTokenParser
;
16 class PackTokenParser
extends AbstractTokenParser
{
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
30 public function __construct(FileLocator
$locator, PackageInterface
$package, $config, $tag, $output, $filters) {
32 $this->locator
= $locator;
35 $this->package
= $package;
38 $this->name
= $config['name'];
41 $this->scheme
= $config['scheme'];
44 $this->timeout
= $config['timeout'];
47 $this->agent
= $config['agent'];
50 $this->redirect
= $config['redirect'];
56 $this->output
= $output;
59 $this->filters
= $filters;
65 * @return string This tag name
67 public function getTag() {
74 * @param Token token The \Twig\Token instance
76 * @return Node The PackNode
78 * @todo see if we can't add a debug mode behaviour
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.
85 * - retrieve fixe link from input s%@(Name)Bundle/Resources/public(/somewhere/file.ext)%/bundles/\L\1\E\2%
87 * - generate a set asset_url=x
90 public function parse(Token
$token) {
91 $parser = $this->parser
;
92 $stream = $this->parser
->getStream();
96 $output = $this->output
;
97 $filters = $this->filters
;
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();
108 } elseif ($stream->test(Token
::NAME_TYPE
, 'filters')) {
111 $stream->expect(Token
::OPERATOR_TYPE
, '=');
112 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(Token
::STRING_TYPE
)->getValue()))));
114 } elseif ($stream->test(Token
::NAME_TYPE
, 'output')) {
115 //output='js/packed/*.js' OR output='js/core.js'
117 $stream->expect(Token
::OPERATOR_TYPE
, '=');
118 $output = $stream->expect(Token
::STRING_TYPE
)->getValue();
120 } elseif ($stream->test(Token
::NAME_TYPE
, 'name')) {
123 $stream->expect(Token
::OPERATOR_TYPE
, '=');
124 $name = $stream->expect(Token
::STRING_TYPE
)->getValue();
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());
133 $stream->expect(Token
::BLOCK_END_TYPE
);
136 $body = $this->parser
->subparse([$this, 'testEndTag'], true);
139 $stream->expect(Token
::BLOCK_END_TYPE
);
141 //TODO: debug mode should be inserted here before the output variable is rewritten
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);
150 for($k = 0; $k < count($inputs); $k++
) {
151 //Deal with generic url
152 if (strpos($inputs[$k], '//') === 0) {
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] == '@') {
160 $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext());
164 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
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());
174 //Replace with glob path
175 array_splice($inputs, $k, 1, $replacement);
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());
186 $ctx = stream_context_create(
189 'timeout' => $this->timeout
,
190 'user_agent' => $this->agent
,
191 'redirect' => $this->redirect
,
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());
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());
212 //Send an empty node without inputs
217 if (!empty($filters)) {
219 foreach($filters as $filter) {
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'];
228 $reflection = new \
ReflectionClass($filter['class']);
230 $tool = $reflection->newInstanceArgs($args);
232 $content = $tool->process($content);
234 unset($tool, $reflection);
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());
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());
248 //Check if we have a bundle path
249 if ($output[0] == '@') {
251 $output = $this->getLocated($output, $token->getLine(), $stream->getSourceContext());
254 //Create output dir if not present
255 if (!is_dir($dir = dirname($output))) {
257 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755)
258 if (mkdir($dir, 0777, true) === false) {
259 throw new \
Exception();
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);
267 //XXX: to avoid partial content in reverse cache we use atomic rotation write, unlink and move
269 if (file_put_contents($output.'.new', $content) === false) {
270 throw new \
Exception();
272 } catch(\Exception
$e) {
273 throw new Error(sprintf('Unable to write to: %s', $output.'.new'), $token->getLine(), $stream->getSourceContext(), $e);
277 if (is_file($output)) {
279 if (unlink($output) === false) {
280 throw new \
Exception();
282 } catch (\Exception
$e) {
283 throw new Error(sprintf('Unable to unlink: %s', $output), $token->getLine(), $stream->getSourceContext(), $e);
289 if (rename($output.'.new', $output) === false) {
290 throw new \
Exception();
292 } catch (\Exception
$e) {
293 throw new Error(sprintf('Unable to rename: %s to %s', $output.'.new', $output), $token->getLine(), $stream->getSourceContext(), $e);
296 //Set name in context key
297 $ref = new AssignNameExpression($name, $token->getLine());
299 //Set output in context value
300 $value = new TextNode($outputUrl, $token->getLine());
302 //Send body with context set
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
314 * @param Token token The \Twig\Token instance
318 public function testEndTag(Token
$token) {
319 return $token->test(['end'.$this->getTag()]);
323 * Get path from bundled file
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
330 * @return string The resolved file path
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');
338 return $this->config['jquery'];
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());
347 $bundle = substr($file, 0, $pos);
350 $path = substr($file, $pos +
1);
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
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;
366 //Resolve bundle prefix
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]);
376 //Detect double bundle suffix
377 if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') {
379 $bundle = substr($bundle, 0, -strlen('Bundle'));
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));
390 //Resolve fixed bundle prefix
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);
400 //Return solved bundle prefix and path
401 return $prefix.$path;