1 <?php 
declare(strict_types
=1); 
   4  * This file is part of the Rapsys PackBundle package. 
   6  * (c) Raphaël Gertz <symfony@rapsys.eu> 
   8  * For the full copyright and license information, please view the LICENSE 
   9  * file that was distributed with this source code. 
  12 namespace Rapsys\PackBundle\Parser
; 
  14 use Symfony\Component\Asset\PackageInterface
; 
  15 use Symfony\Component\Filesystem\Exception\IOExceptionInterface
; 
  16 use Symfony\Component\Filesystem\Filesystem
; 
  17 use Symfony\Component\HttpKernel\Config\FileLocator
; 
  20 use Twig\Node\Expression\AssignNameExpression
; 
  22 use Twig\Node\SetNode
; 
  23 use Twig\Node\TextNode
; 
  26 use Twig\TokenParser\AbstractTokenParser
; 
  28 class TokenParser 
extends AbstractTokenParser 
{ 
  62          * @param FileLocator $locator The FileLocator instance 
  63          * @param PackageInterface $package The Assets Package instance 
  64          * @param array $config The config path 
  65          * @param string $tag The tag name 
  66          * @param string $output The default output string 
  67          * @param array $filters The default filters array 
  69         public function __construct(FileLocator 
$locator, PackageInterface 
$package, array $config, string $tag, string $output, array $filters) { 
  71                 $this->locator 
= $locator; 
  74                 $this->package 
= $package; 
  77                 $this->name 
= $config['name']; 
  80                 $this->scheme 
= $config['scheme']; 
  83                 $this->timeout 
= $config['timeout']; 
  86                 $this->agent 
= $config['agent']; 
  89                 $this->redirect 
= $config['redirect']; 
  95                 $this->output 
= $output; 
  98                 $this->filters 
= $filters; 
 104          * @return string This tag name 
 106         public function getTag(): string { 
 113          * @xxx Skip filter when debug mode is enabled is not possible 
 114          * @xxx This code is only run once when twig cache is enabled 
 115          * @xxx Twig cache value is not avaible in container parameters, maybe in twig env ? 
 117          * @param Token $token The \Twig\Token instance 
 118          * @return Node The PackNode 
 120         public function parse(Token 
$token): Node 
{ 
 121                 $parser = $this->parser
; 
 122                 $stream = $this->parser
->getStream(); 
 126                 $output = $this->output
; 
 127                 $filters = $this->filters
; 
 131                 //Process the token block until end 
 132                 while (!$stream->test(Token
::BLOCK_END_TYPE
)) { 
 133                         //The files to process 
 134                         if ($stream->test(Token
::STRING_TYPE
)) { 
 135                                 //'somewhere/somefile.(css,img,js)' 'somewhere/*' '@jquery' 
 136                                 $inputs[] = $stream->next()->getValue(); 
 138                         } elseif ($stream->test(Token
::NAME_TYPE
, 'filters')) { 
 141                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 142                                 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(Token
::STRING_TYPE
)->getValue())))); 
 144                         } elseif ($stream->test(Token
::NAME_TYPE
, 'output')) { 
 145                                 //output='js/packed/*.js' OR output='js/core.js' 
 147                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 148                                 $output = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 150                         } elseif ($stream->test(Token
::NAME_TYPE
, 'name')) { 
 153                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 154                                 $name = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 157                                 $token = $stream->getCurrent(); 
 158                                 throw new Error(sprintf('Unexpected token "%s" of value "%s"', Token
::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext()); 
 163                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 166                 $body = $this->parser
->subparse([$this, 'testEndTag'], true); 
 169                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 171                 //Replace star with sha1 
 172                 if (($pos = strpos($output, '*')) !== false) { 
 173                         //XXX: assetic use substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7) 
 174                         $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 
1); 
 178                 for($k = 0; $k < count($inputs); $k++
) { 
 179                         //Deal with generic url 
 180                         if (strpos($inputs[$k], '//') === 0) { 
 182                                 $inputs[$k] = $this->scheme
.substr($inputs[$k], 2); 
 183                         //Deal with non url path 
 184                         } elseif (strpos($inputs[$k], '://') === false) { 
 185                                 //Check if we have a bundle path 
 186                                 if ($inputs[$k][0] == '@') { 
 188                                         $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext()); 
 192                                 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) { 
 194                                         $replacement = glob($inputs[$k], GLOB_NOSORT
|GLOB_BRACE
); 
 195                                         //Check that these are working files 
 196                                         foreach($replacement as $input) { 
 197                                                 //Check that it's a file 
 198                                                 if (!is_file($input)) { 
 199                                                         throw new Error(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 202                                         //Replace with glob path 
 203                                         array_splice($inputs, $k, 1, $replacement); 
 205                                         $k +
= count($replacement) - 1; 
 206                                 //Check that it's a file 
 207                                 } elseif (!is_file($inputs[$k])) { 
 208                                         throw new Error(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 214                 $ctx = stream_context_create( 
 217                                         'timeout' => $this->timeout
, 
 218                                         'user_agent' => $this->agent
, 
 219                                         'redirect' => $this->redirect
, 
 225                 if (!empty($inputs)) { 
 226                         //Retrieve files content 
 227                         foreach($inputs as $input) { 
 228                                 //Try to retrieve content 
 229                                 if (($data = file_get_contents($input, false, $ctx)) === false) { 
 230                                         throw new Error(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext()); 
 236                         //Trigger error about empty inputs ? 
 237                         //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 
 238                         #throw new Error('Empty inputs token', $token->getLine(), $stream->getSourceContext()); 
 240                         //Send an empty node without inputs 
 245                 if (!empty($filters)) { 
 247                         foreach($filters as $filter) { 
 249                                 $args = [$stream->getSourceContext(), $token->getLine()]; 
 250                                 //Check if args is available 
 251                                 if (!empty($filter['args'])) { 
 252                                         //Append args if provided 
 253                                         $args +
= $filter['args']; 
 256                                 $reflection = new \
ReflectionClass($filter['class']); 
 258                                 $tool = $reflection->newInstanceArgs($args); 
 260                                 $content = $tool->process($content); 
 262                                 unset($tool, $reflection); 
 265                         //Trigger error about empty filters ? 
 266                         //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 
 267                         #throw new Error('Empty filters token', $token->getLine(), $stream->getSourceContext()); 
 271                 //XXX: this path is the merge of services.assets.path_package.arguments[0] and rapsys_pack.output.(css,img,js) 
 272                 if (($outputUrl = $this->package
->getUrl($output)) === false) { 
 273                         throw new Error(sprintf('Unable to get url for asset: %s', $output), $token->getLine(), $stream->getSourceContext()); 
 276                 //Check if we have a bundle path 
 277                 if ($output[0] == '@') { 
 279                         $output = $this->getLocated($output, $token->getLine(), $stream->getSourceContext()); 
 283                 $filesystem = new Filesystem(); 
 285                 //Create output dir if not present 
 286                 if (!is_dir($dir = dirname($output))) { 
 289                                 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 290                                 $filesystem->mkdir($dir, 0775); 
 291                         } catch (IOExceptionInterface 
$e) { 
 293                                 throw new Error(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext(), $e); 
 299                         //Write content to file 
 300                         //XXX: this call is (maybe) atomic 
 301                         //XXX: see https://symfony.com/doc/current/components/filesystem.html#dumpfile 
 302                         $filesystem->dumpFile($output, $content); 
 303                 } catch (IOExceptionInterface 
$e) { 
 305                         throw new Error(sprintf('Unable to write to: %s', $output), $token->getLine(), $stream->getSourceContext(), $e); 
 308                 //Set name in context key 
 309                 $ref = new AssignNameExpression($name, $token->getLine()); 
 311                 //Set output in context value 
 312                 $value = new TextNode($outputUrl, $token->getLine()); 
 314                 //Send body with context set 
 316                         //This define name in twig template by prepending $context['<name>'] = '<output>'; 
 317                         new SetNode(true, $ref, $value, $token->getLine(), $this->getTag()), 
 318                         //The tag captured body 
 326          * @param Token $token The \Twig\Token instance 
 327          * @return bool The token end test result 
 329         public function testEndTag(Token 
$token): bool { 
 330                 return $token->test(['end'.$this->getTag()]); 
 334          * Get path from bundled file 
 336          * @see https://symfony.com/doc/current/bundles.html#overridding-the-bundle-directory-structure 
 338          * @param string $file The bundled file path 
 339          * @param int $lineno The template line where the error occurred 
 340          * @param Source $source The source context where the error occurred 
 341          * @param Exception $prev The previous exception 
 342          * @return string The resolved file path 
 344         public function getLocated(string $file, int $lineno = 0, Source 
$source = null, \Exception 
$prev = null): string { 
 345                 /*TODO: add a @jquery magic feature ? 
 346                 if ($file == '@jquery') { 
 347                         #header('Content-Type: text/plain'); 
 350                         return $this->config['jquery']; 
 353                 //Check that we have a / separator between bundle name and path 
 354                 if (($pos = strpos($file, '/')) === false) { 
 355                         throw new Error(sprintf('Invalid path "%s"', $file), $token->getLine(), $stream->getSourceContext()); 
 359                 $bundle = substr($file, 0, $pos); 
 362                 $path = substr($file, $pos + 
1); 
 364                 //Check for bundle suffix presence 
 365                 //XXX: use "bundle templates automatic namespace" mimicked behaviour to find intended bundle and/or path 
 366                 //XXX: see https://symfony.com/doc/4.3/templates.html#bundle-templates 
 367                 if (strlen($bundle) < strlen('Bundle') || substr($bundle, -strlen('Bundle')) !== 'Bundle') { 
 368                         //Append Bundle in an attempt to fix it's naming for locator 
 371                         //Check for public resource prefix presence 
 372                         if (strlen($path) < strlen('Resources/public') || substr($path, 0, strlen('Resources/public')) != 'Resources/public') { 
 373                                 //Prepend standard public path 
 374                                 $path = 'Resources/public/'.$path; 
 378                 //Resolve bundle prefix 
 380                         $prefix = $this->locator
->locate($bundle); 
 381                 //Catch bundle does not exist or is not enabled exception 
 382                 } catch(\InvalidArgumentException 
$e) { 
 383                         //Fix lowercase first bundle character 
 384                         if ($bundle[1] > 'Z' || $bundle[1] < 'A') { 
 385                                 $bundle[1] = strtoupper($bundle[1]); 
 388                         //Detect double bundle suffix 
 389                         if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') { 
 391                                 $bundle = substr($bundle, 0, -strlen('Bundle')); 
 394                         //Convert snake case in camel case 
 395                         if (strpos($bundle, '_') !== false) { 
 396                                 //Fix every first character following a _ 
 397                                 while(($cur = strpos($bundle, '_')) !== false) { 
 398                                         $bundle = substr($bundle, 0, $cur).ucfirst(substr($bundle, $cur + 
1)); 
 402                         //Resolve fixed bundle prefix 
 404                                 $prefix = $this->locator
->locate($bundle); 
 405                                 //Catch bundle does not exist or is not enabled exception again 
 406                         } catch(\InvalidArgumentException 
$e) { 
 407                                 //Bail out as bundle or path is invalid and we have no way to know what was meant 
 408                                 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); 
 412                 //Return solved bundle prefix and path 
 413                 return $prefix.$path;