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 
{ 
  35          * @param FileLocator $locator The FileLocator instance 
  36          * @param PackageInterface $package The Assets Package instance 
  37          * @param array $config The config path 
  38          * @param string $tag The tag name 
  39          * @param string $output The default output string 
  40          * @param array $filters The default filters array 
  42         public function __construct(FileLocator 
$locator, PackageInterface 
$package, array $config, string $tag, string $output, array $filters) { 
  44                 $this->locator 
= $locator; 
  47                 $this->package 
= $package; 
  50                 $this->name 
= $config['name']; 
  53                 $this->scheme 
= $config['scheme']; 
  56                 $this->timeout 
= $config['timeout']; 
  59                 $this->agent 
= $config['agent']; 
  62                 $this->redirect 
= $config['redirect']; 
  68                 $this->output 
= $output; 
  71                 $this->filters 
= $filters; 
  77          * @return string This tag name 
  79         public function getTag(): string { 
  86          * @xxx Skip filter when debug mode is enabled is not possible 
  87          * @xxx This code is only run once when twig cache is enabled 
  88          * @xxx Twig cache value is not avaible in container parameters, maybe in twig env ? 
  90          * @param Token $token The \Twig\Token instance 
  91          * @return Node The PackNode 
  93         public function parse(Token 
$token): Node 
{ 
  94                 $parser = $this->parser
; 
  95                 $stream = $this->parser
->getStream(); 
  99                 $output = $this->output
; 
 100                 $filters = $this->filters
; 
 104                 //Process the token block until end 
 105                 while (!$stream->test(Token
::BLOCK_END_TYPE
)) { 
 106                         //The files to process 
 107                         if ($stream->test(Token
::STRING_TYPE
)) { 
 108                                 //'somewhere/somefile.(css,img,js)' 'somewhere/*' '@jquery' 
 109                                 $inputs[] = $stream->next()->getValue(); 
 111                         } elseif ($stream->test(Token
::NAME_TYPE
, 'filters')) { 
 114                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 115                                 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(Token
::STRING_TYPE
)->getValue())))); 
 117                         } elseif ($stream->test(Token
::NAME_TYPE
, 'output')) { 
 118                                 //output='js/packed/*.js' OR output='js/core.js' 
 120                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 121                                 $output = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 123                         } elseif ($stream->test(Token
::NAME_TYPE
, 'name')) { 
 126                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 127                                 $name = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 130                                 $token = $stream->getCurrent(); 
 131                                 throw new Error(sprintf('Unexpected token "%s" of value "%s"', Token
::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext()); 
 136                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 139                 $body = $this->parser
->subparse([$this, 'testEndTag'], true); 
 142                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 144                 //Replace star with sha1 
 145                 if (($pos = strpos($output, '*')) !== false) { 
 146                         //XXX: assetic use substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7) 
 147                         $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 
1); 
 151                 for($k = 0; $k < count($inputs); $k++
) { 
 152                         //Deal with generic url 
 153                         if (strpos($inputs[$k], '//') === 0) { 
 155                                 $inputs[$k] = $this->scheme
.substr($inputs[$k], 2); 
 156                         //Deal with non url path 
 157                         } elseif (strpos($inputs[$k], '://') === false) { 
 158                                 //Check if we have a bundle path 
 159                                 if ($inputs[$k][0] == '@') { 
 161                                         $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext()); 
 165                                 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) { 
 167                                         $replacement = glob($inputs[$k], GLOB_NOSORT
|GLOB_BRACE
); 
 168                                         //Check that these are working files 
 169                                         foreach($replacement as $input) { 
 170                                                 //Check that it's a file 
 171                                                 if (!is_file($input)) { 
 172                                                         throw new Error(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 175                                         //Replace with glob path 
 176                                         array_splice($inputs, $k, 1, $replacement); 
 178                                         $k +
= count($replacement) - 1; 
 179                                 //Check that it's a file 
 180                                 } elseif (!is_file($inputs[$k])) { 
 181                                         throw new Error(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 187                 $ctx = stream_context_create( 
 190                                         'timeout' => $this->timeout
, 
 191                                         'user_agent' => $this->agent
, 
 192                                         'redirect' => $this->redirect
, 
 198                 if (!empty($inputs)) { 
 199                         //Retrieve files content 
 200                         foreach($inputs as $input) { 
 201                                 //Try to retrieve content 
 202                                 if (($data = file_get_contents($input, false, $ctx)) === false) { 
 203                                         throw new Error(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext()); 
 209                         //Trigger error about empty inputs ? 
 210                         //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 
 211                         #throw new Error('Empty inputs token', $token->getLine(), $stream->getSourceContext()); 
 213                         //Send an empty node without inputs 
 218                 if (!empty($filters)) { 
 220                         foreach($filters as $filter) { 
 222                                 $args = [$stream->getSourceContext(), $token->getLine()]; 
 223                                 //Check if args is available 
 224                                 if (!empty($filter['args'])) { 
 225                                         //Append args if provided 
 226                                         $args +
= $filter['args']; 
 229                                 $reflection = new \
ReflectionClass($filter['class']); 
 231                                 $tool = $reflection->newInstanceArgs($args); 
 233                                 $content = $tool->process($content); 
 235                                 unset($tool, $reflection); 
 238                         //Trigger error about empty filters ? 
 239                         //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 
 240                         #throw new Error('Empty filters token', $token->getLine(), $stream->getSourceContext()); 
 244                 //XXX: this path is the merge of services.assets.path_package.arguments[0] and rapsys_pack.output.(css,img,js) 
 245                 if (($outputUrl = $this->package
->getUrl($output)) === false) { 
 246                         throw new Error(sprintf('Unable to get url for asset: %s', $output), $token->getLine(), $stream->getSourceContext()); 
 249                 //Check if we have a bundle path 
 250                 if ($output[0] == '@') { 
 252                         $output = $this->getLocated($output, $token->getLine(), $stream->getSourceContext()); 
 256                 $filesystem = new Filesystem(); 
 258                 //Create output dir if not present 
 259                 if (!is_dir($dir = dirname($output))) { 
 262                                 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 263                                 $filesystem->mkdir($dir, 0775); 
 264                         } catch (IOExceptionInterface 
$e) { 
 266                                 throw new Error(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext(), $e); 
 272                         //Write content to file 
 273                         //XXX: this call is (maybe) atomic 
 274                         //XXX: see https://symfony.com/doc/current/components/filesystem.html#dumpfile 
 275                         $filesystem->dumpFile($output, $content); 
 276                 } catch (IOExceptionInterface 
$e) { 
 278                         throw new Error(sprintf('Unable to write to: %s', $output), $token->getLine(), $stream->getSourceContext(), $e); 
 281                 //Set name in context key 
 282                 $ref = new AssignNameExpression($name, $token->getLine()); 
 284                 //Set output in context value 
 285                 $value = new TextNode($outputUrl, $token->getLine()); 
 287                 //Send body with context set 
 289                         //This define name in twig template by prepending $context['<name>'] = '<output>'; 
 290                         new SetNode(true, $ref, $value, $token->getLine(), $this->getTag()), 
 291                         //The tag captured body 
 299          * @param Token $token The \Twig\Token instance 
 300          * @return bool The token end test result 
 302         public function testEndTag(Token 
$token): bool { 
 303                 return $token->test(['end'.$this->getTag()]); 
 307          * Get path from bundled file 
 309          * @see https://symfony.com/doc/current/bundles.html#overridding-the-bundle-directory-structure 
 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 
 315          * @return string The resolved file path 
 317         public function getLocated(string $file, int $lineno = 0, Source 
$source = null, \Exception 
$prev = null): string { 
 318                 /*TODO: add a @jquery magic feature ? 
 319                 if ($file == '@jquery') { 
 320                         #header('Content-Type: text/plain'); 
 323                         return $this->config['jquery']; 
 326                 //Check that we have a / separator between bundle name and path 
 327                 if (($pos = strpos($file, '/')) === false) { 
 328                         throw new Error(sprintf('Invalid path "%s"', $file), $token->getLine(), $stream->getSourceContext()); 
 332                 $bundle = substr($file, 0, $pos); 
 335                 $path = substr($file, $pos + 
1); 
 337                 //Check for bundle suffix presence 
 338                 //XXX: use "bundle templates automatic namespace" mimicked behaviour to find intended bundle and/or path 
 339                 //XXX: see https://symfony.com/doc/4.3/templates.html#bundle-templates 
 340                 if (strlen($bundle) < strlen('Bundle') || substr($bundle, -strlen('Bundle')) !== 'Bundle') { 
 341                         //Append Bundle in an attempt to fix it's naming for locator 
 344                         //Check for public resource prefix presence 
 345                         if (strlen($path) < strlen('Resources/public') || substr($path, 0, strlen('Resources/public')) != 'Resources/public') { 
 346                                 //Prepend standard public path 
 347                                 $path = 'Resources/public/'.$path; 
 351                 //Resolve bundle prefix 
 353                         $prefix = $this->locator
->locate($bundle); 
 354                 //Catch bundle does not exist or is not enabled exception 
 355                 } catch(\InvalidArgumentException 
$e) { 
 356                         //Fix lowercase first bundle character 
 357                         if ($bundle[1] > 'Z' || $bundle[1] < 'A') { 
 358                                 $bundle[1] = strtoupper($bundle[1]); 
 361                         //Detect double bundle suffix 
 362                         if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') { 
 364                                 $bundle = substr($bundle, 0, -strlen('Bundle')); 
 367                         //Convert snake case in camel case 
 368                         if (strpos($bundle, '_') !== false) { 
 369                                 //Fix every first character following a _ 
 370                                 while(($cur = strpos($bundle, '_')) !== false) { 
 371                                         $bundle = substr($bundle, 0, $cur).ucfirst(substr($bundle, $cur + 
1)); 
 375                         //Resolve fixed bundle prefix 
 377                                 $prefix = $this->locator
->locate($bundle); 
 378                                 //Catch bundle does not exist or is not enabled exception again 
 379                         } catch(\InvalidArgumentException 
$e) { 
 380                                 //Bail out as bundle or path is invalid and we have no way to know what was meant 
 381                                 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); 
 385                 //Return solved bundle prefix and path 
 386                 return $prefix.$path;