3 namespace Rapsys\PackBundle\Twig
; 
   5 use Symfony\Component\Asset\PackageInterface
; 
   6 use Symfony\Component\Filesystem\Exception\IOExceptionInterface
; 
   7 use Symfony\Component\Filesystem\Filesystem
; 
   8 use Symfony\Component\HttpKernel\Config\FileLocator
; 
  10 use Twig\Node\Expression\AssignNameExpression
; 
  12 use Twig\Node\SetNode
; 
  13 use Twig\Node\TextNode
; 
  16 use Twig\TokenParser\AbstractTokenParser
; 
  18 class PackTokenParser 
extends AbstractTokenParser 
{ 
  25          * @param FileLocator      locator The FileLocator instance 
  26          * @param PackageInterface package The Assets Package instance 
  27          * @param array            config  The config path 
  28          * @param string           tag     The tag name 
  29          * @param string           output  The default output string 
  30          * @param array            filters The default filters array 
  32         public function __construct(FileLocator 
$locator, PackageInterface 
$package, $config, $tag, $output, $filters) { 
  34                 $this->locator 
= $locator; 
  37                 $this->package 
= $package; 
  40                 $this->name 
= $config['name']; 
  43                 $this->scheme 
= $config['scheme']; 
  46                 $this->timeout 
= $config['timeout']; 
  49                 $this->agent 
= $config['agent']; 
  52                 $this->redirect 
= $config['redirect']; 
  58                 $this->output 
= $output; 
  61                 $this->filters 
= $filters; 
  67          * @return string This tag name 
  69         public function getTag() { 
  76          * @param Token token The \Twig\Token instance 
  78          * @return Node The PackNode 
  80          * @todo see if we can't add a debug mode behaviour 
  82          * If twig.debug or env=dev (or rapsys_pack.config.debug?) is set, it should be possible to loop on each input 
  83          * and process the captured body without applying requested filter. 
  87          * - retrieve fixe link from input s%@(Name)Bundle/Resources/public(/somewhere/file.ext)%/bundles/\L\1\E\2% 
  89          *   - generate a set asset_url=x 
  92         public function parse(Token 
$token) { 
  93                 $parser = $this->parser
; 
  94                 $stream = $this->parser
->getStream(); 
  98                 $output = $this->output
; 
  99                 $filters = $this->filters
; 
 103                 //Process the token block until end 
 104                 while (!$stream->test(Token
::BLOCK_END_TYPE
)) { 
 105                         //The files to process 
 106                         if ($stream->test(Token
::STRING_TYPE
)) { 
 107                                 //'somewhere/somefile.(css,img,js)' 'somewhere/*' '@jquery' 
 108                                 $inputs[] = $stream->next()->getValue(); 
 110                         } elseif ($stream->test(Token
::NAME_TYPE
, 'filters')) { 
 113                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 114                                 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(Token
::STRING_TYPE
)->getValue())))); 
 116                         } elseif ($stream->test(Token
::NAME_TYPE
, 'output')) { 
 117                                 //output='js/packed/*.js' OR output='js/core.js' 
 119                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 120                                 $output = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 122                         } elseif ($stream->test(Token
::NAME_TYPE
, 'name')) { 
 125                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 126                                 $name = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 129                                 $token = $stream->getCurrent(); 
 130                                 throw new Error(sprintf('Unexpected token "%s" of value "%s"', Token
::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext()); 
 135                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 138                 $body = $this->parser
->subparse([$this, 'testEndTag'], true); 
 141                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 143                 //TODO: debug mode should be inserted here before the output variable is rewritten 
 145                 //Replace star with sha1 
 146                 if (($pos = strpos($output, '*')) !== false) { 
 147                         //XXX: assetic use substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7) 
 148                         $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 
1); 
 152                 for($k = 0; $k < count($inputs); $k++
) { 
 153                         //Deal with generic url 
 154                         if (strpos($inputs[$k], '//') === 0) { 
 156                                 $inputs[$k] = $this->scheme
.substr($inputs[$k], 2); 
 157                         //Deal with non url path 
 158                         } elseif (strpos($inputs[$k], '://') === false) { 
 159                                 //Check if we have a bundle path 
 160                                 if ($inputs[$k][0] == '@') { 
 162                                         $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext()); 
 166                                 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) { 
 168                                         $replacement = glob($inputs[$k], GLOB_NOSORT
|GLOB_BRACE
); 
 169                                         //Check that these are working files 
 170                                         foreach($replacement as $input) { 
 171                                                 //Check that it's a file 
 172                                                 if (!is_file($input)) { 
 173                                                         throw new Error(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 176                                         //Replace with glob path 
 177                                         array_splice($inputs, $k, 1, $replacement); 
 179                                         $k +
= count($replacement) - 1; 
 180                                 //Check that it's a file 
 181                                 } elseif (!is_file($inputs[$k])) { 
 182                                         throw new Error(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 188                 $ctx = stream_context_create( 
 191                                         'timeout' => $this->timeout
, 
 192                                         'user_agent' => $this->agent
, 
 193                                         'redirect' => $this->redirect
, 
 199                 if (!empty($inputs)) { 
 200                         //Retrieve files content 
 201                         foreach($inputs as $input) { 
 202                                 //Try to retrieve content 
 203                                 if (($data = file_get_contents($input, false, $ctx)) === false) { 
 204                                         throw new Error(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext()); 
 210                         //Trigger error about empty inputs ? 
 211                         //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 
 212                         #throw new Error('Empty inputs token', $token->getLine(), $stream->getSourceContext()); 
 214                         //Send an empty node without inputs 
 219                 if (!empty($filters)) { 
 221                         foreach($filters as $filter) { 
 223                                 $args = [$stream->getSourceContext(), $token->getLine()]; 
 224                                 //Check if args is available 
 225                                 if (!empty($filter['args'])) { 
 226                                         //Append args if provided 
 227                                         $args +
= $filter['args']; 
 230                                 $reflection = new \
ReflectionClass($filter['class']); 
 232                                 $tool = $reflection->newInstanceArgs($args); 
 234                                 $content = $tool->process($content); 
 236                                 unset($tool, $reflection); 
 239                         //Trigger error about empty filters ? 
 240                         //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 
 241                         #throw new Error('Empty filters token', $token->getLine(), $stream->getSourceContext()); 
 245                 //XXX: this path is the merge of services.assets.path_package.arguments[0] and rapsys_pack.output.(css,img,js) 
 246                 if (($outputUrl = $this->package
->getUrl($output)) === false) { 
 247                         throw new Error(sprintf('Unable to get url for asset: %s', $output), $token->getLine(), $stream->getSourceContext()); 
 250                 //Check if we have a bundle path 
 251                 if ($output[0] == '@') { 
 253                         $output = $this->getLocated($output, $token->getLine(), $stream->getSourceContext()); 
 257                 $filesystem = new Filesystem(); 
 259                 //Create output dir if not present 
 260                 if (!is_dir($dir = dirname($output))) { 
 263                                 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 264                             $filesystem->mkdir($dir, 0775); 
 265                         } catch (IOExceptionInterface 
$e) { 
 267                                 throw new Error(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext(), $e); 
 273                         //Write content to file 
 274                         //XXX: this call is (maybe) atomic 
 275                         //XXX: see https://symfony.com/doc/current/components/filesystem.html#dumpfile 
 276                         $filesystem->dumpFile($output, $content); 
 277                 } catch (IOExceptionInterface 
$e) { 
 279                         throw new Error(sprintf('Unable to write to: %s', $output), $token->getLine(), $stream->getSourceContext(), $e); 
 282                 //Set name in context key 
 283                 $ref = new AssignNameExpression($name, $token->getLine()); 
 285                 //Set output in context value 
 286                 $value = new TextNode($outputUrl, $token->getLine()); 
 288                 //Send body with context set 
 290                         //This define name in twig template by prepending $context['<name>'] = '<output>'; 
 291                         new SetNode(true, $ref, $value, $token->getLine(), $this->getTag()), 
 292                         //The tag captured body 
 300          * @param Token token The \Twig\Token instance 
 304         public function testEndTag(Token 
$token) { 
 305                 return $token->test(['end'.$this->getTag()]); 
 309          * Get path from bundled file 
 311          * @param string     file   The bundled file path 
 312          * @param int        lineno The template line where the error occurred 
 313          * @param Source     source The source context where the error occurred 
 314          * @param \Exception prev   The previous exception 
 316          * @return string The resolved file path 
 318          * @todo Try retrive public dir from the member function BundleNameBundle::getPublicDir() return value ? 
 319          * @xxx see https://symfony.com/doc/current/bundles.html#overridding-the-bundle-directory-structure 
 321         public function getLocated($file, int $lineno = 0, Source 
$source = null, \Exception 
$prev = null) { 
 322                 /*TODO: add a @jquery magic feature ? 
 323                 if ($file == '@jquery') { 
 324                         #header('Content-Type: text/plain'); 
 327                         return $this->config['jquery']; 
 330                 //Check that we have a / separator between bundle name and path 
 331                 if (($pos = strpos($file, '/')) === false) { 
 332                         throw new Error(sprintf('Invalid path "%s"', $file), $token->getLine(), $stream->getSourceContext()); 
 336                 $bundle = substr($file, 0, $pos); 
 339                 $path = substr($file, $pos + 
1); 
 341                 //Check for bundle suffix presence 
 342                 //XXX: use "bundle templates automatic namespace" mimicked behaviour to find intended bundle and/or path 
 343                 //XXX: see https://symfony.com/doc/4.3/templates.html#bundle-templates 
 344                 if (strlen($bundle) < strlen('Bundle') || substr($bundle, -strlen('Bundle')) !== 'Bundle') { 
 345                         //Append Bundle in an attempt to fix it's naming for locator 
 348                         //Check for public resource prefix presence 
 349                         if (strlen($path) < strlen('Resources/public') || substr($path, 0, strlen('Resources/public')) != 'Resources/public') { 
 350                                 //Prepend standard public path 
 351                                 $path = 'Resources/public/'.$path; 
 355                 //Resolve bundle prefix 
 357                         $prefix = $this->locator
->locate($bundle); 
 358                         //Catch bundle does not exist or is not enabled exception 
 359                 } catch(\InvalidArgumentException 
$e) { 
 360                         //Fix lowercase first bundle character 
 361                         if ($bundle[1] > 'Z' || $bundle[1] < 'A') { 
 362                                 $bundle[1] = strtoupper($bundle[1]); 
 365                         //Detect double bundle suffix 
 366                         if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') { 
 368                                 $bundle = substr($bundle, 0, -strlen('Bundle')); 
 371                         //Convert snake case in camel case 
 372                         if (strpos($bundle, '_') !== false) { 
 373                                 //Fix every first character following a _ 
 374                                 while(($cur = strpos($bundle, '_')) !== false) { 
 375                                         $bundle = substr($bundle, 0, $cur).ucfirst(substr($bundle, $cur + 
1)); 
 379                         //Resolve fixed bundle prefix 
 381                                 $prefix = $this->locator
->locate($bundle); 
 382                                 //Catch bundle does not exist or is not enabled exception again 
 383                         } catch(\InvalidArgumentException 
$e) { 
 384                                 //Bail out as bundle or path is invalid and we have no way to know what was meant 
 385                                 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); 
 389                 //Return solved bundle prefix and path 
 390                 return $prefix.$path;