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 use Rapsys\PackBundle\RapsysPackBundle
; 
  33 class TokenParser 
extends AbstractTokenParser 
{ 
  35          * The stream context instance 
  42          * @param FileLocator $locator The FileLocator instance 
  43          * @param PackageInterface $package The Assets Package instance 
  44          * @param string $token The token name 
  45          * @param string $tag The tag name 
  46          * @param string $output The default output string 
  47          * @param array $filters The default filter array 
  49         public function __construct(protected FileLocator 
$locator, protected PackageInterface 
$package, protected string $token, protected string $tag, protected string $output, protected array $filters) { 
  51                 $this->ctx 
= stream_context_create( 
  54                                         #'header' => ['Referer: https://www.openstreetmap.org/'], 
  55                                         'max_redirects' => $_ENV['RAPSYSPACK_REDIRECT'] ?? 20, 
  56                                         'timeout' => $_ENV['RAPSYSPACK_TIMEOUT'] ?? (($timeout = ini_get('default_socket_timeout')) !== false && $timeout !== "" ? (float)$timeout : 60), 
  57                                         'user_agent' => $_ENV['RAPSYSPACK_AGENT'] ?? (($agent = ini_get('user_agent')) !== false && $agent !== "" ? (string)$agent : RapsysPackBundle
::getAlias().'/'.RapsysPackBundle
::getVersion()) 
  66          * @return string This tag name 
  68         public function getTag(): string { 
  75          * @xxx Skip filter when debug mode is enabled is not possible 
  76          * @xxx This code is only run once when twig cache is enabled 
  77          * @xxx Twig cache value is not avaible in container parameters, maybe in twig env ? 
  79          * @param Token $token The \Twig\Token instance 
  80          * @return Node The PackNode 
  82         public function parse(Token 
$token): Node 
{ 
  84                 $parser = $this->parser
; 
  87                 $stream = $this->parser
->getStream(); 
  95                 //Process the token block until end 
  96                 while (!$stream->test(Token
::BLOCK_END_TYPE
)) { 
  97                         //The files to process 
  98                         if ($stream->test(Token
::STRING_TYPE
)) { 
  99                                 //'somewhere/somefile.(css,img,js)' 'somewhere/*' '@jquery' 
 100                                 $inputs[] = $stream->next()->getValue(); 
 102                         } elseif ($stream->test(Token
::NAME_TYPE
, 'filters')) { 
 105                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 106                                 $this->filters 
= array_merge($this->filters
, array_filter(array_map('trim', explode(',', $stream->expect(Token
::STRING_TYPE
)->getValue())))); 
 108                         } elseif ($stream->test(Token
::NAME_TYPE
, 'output')) { 
 109                                 //output='js/packed/*.js' OR output='js/core.js' 
 111                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 112                                 $this->output 
= $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 114                         } elseif ($stream->test(Token
::NAME_TYPE
, 'token')) { 
 117                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 118                                 $this->token 
= $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 121                                 $token = $stream->getCurrent(); 
 122                                 throw new Error(sprintf('Unexpected token "%s" of value "%s"', Token
::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext()); 
 127                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 130                 $body = $this->parser
->subparse([$this, 'testEndTag'], true); 
 133                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 135                 //Replace star with sha1 
 136                 if (($pos = strpos($this->output
, '*')) !== false) { 
 137                         //XXX: assetic use substr(sha1(serialize($inputs).serialize($this->filters).serialize($this->output)), 0, 7) 
 138                         $this->output 
= substr($this->output
, 0, $pos).sha1(serialize($inputs).serialize($this->filters
)).substr($this->output
, $pos + 
1); 
 142                 for($k = 0; $k < count($inputs); $k++
) { 
 143                         //Deal with generic url 
 144                         if (strpos($inputs[$k], '//') === 0) { 
 146                                 $inputs[$k] = ($_ENV['RAPSYSPACK_SCHEME'] ?? 'https://').substr($inputs[$k], 2); 
 147                         //Deal with non url path 
 148                         } elseif (strpos($inputs[$k], '://') === false) { 
 149                                 //Check if we have a bundle path 
 150                                 if ($inputs[$k][0] == '@') { 
 152                                         $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext()); 
 156                                 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) { 
 158                                         $replacement = glob($inputs[$k], GLOB_NOSORT
|GLOB_BRACE
); 
 160                                         //Check that these are working files 
 161                                         foreach($replacement as $input) { 
 162                                                 //Check that it's a file 
 163                                                 if (!is_file($input)) { 
 164                                                         throw new Error(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 168                                         //Replace with glob path 
 169                                         array_splice($inputs, $k, 1, $replacement); 
 172                                         $k +
= count($replacement) - 1; 
 173                                 //Check that it's a file 
 174                                 } elseif (!is_file($inputs[$k])) { 
 175                                         throw new Error(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 181                 if (!empty($inputs)) { 
 182                         //Retrieve files content 
 183                         foreach($inputs as $input) { 
 184                                 //Try to retrieve content 
 185                                 if (($data = file_get_contents($input, false, $this->ctx
)) === false) { 
 186                                         throw new Error(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext()); 
 193                         //Trigger error about empty inputs ? 
 194                         //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 
 195                         #throw new Error('Empty inputs token', $token->getLine(), $stream->getSourceContext()); 
 197                         //Send an empty node without inputs 
 202                 if (!empty($this->filters
)) { 
 204                         foreach($this->filters 
as $filter) { 
 206                                 $args = [$stream->getSourceContext(), $token->getLine()]; 
 208                                 //Check if args is available 
 209                                 if (!empty($filter['args'])) { 
 210                                         //Append args if provided 
 211                                         $args +
= $filter['args']; 
 215                                 $reflection = new \
ReflectionClass($filter['class']); 
 218                                 $tool = $reflection->newInstanceArgs($args); 
 221                                 $content = $tool->process($content); 
 224                                 unset($tool, $reflection); 
 227                         //Trigger error about empty filters ? 
 228                         //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 
 229                         #throw new Error('Empty filters token', $token->getLine(), $stream->getSourceContext()); 
 233                 //XXX: this path is the merge of services.assets.path_package.arguments[0] and rapsyspack.output.(css,img,js) 
 234                 if (($outputUrl = $this->package
->getUrl($this->output
)) === false) { 
 235                         throw new Error(sprintf('Unable to get url for asset: %s', $this->output
), $token->getLine(), $stream->getSourceContext()); 
 238                 //Check if we have a bundle path 
 239                 if ($this->output
[0] == '@') { 
 241                         $this->output 
= $this->getLocated($this->output
, $token->getLine(), $stream->getSourceContext()); 
 245                 $filesystem = new Filesystem(); 
 247                 //Create output dir if not present 
 248                 if (!is_dir($dir = dirname($this->output
))) { 
 251                                 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755) 
 252                                 $filesystem->mkdir($dir, 0775); 
 253                         } catch (IOExceptionInterface 
$e) { 
 255                                 throw new Error(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext(), $e); 
 261                         //Write content to file 
 262                         //XXX: this call is (maybe) atomic 
 263                         //XXX: see https://symfony.com/doc/current/components/filesystem.html#dumpfile 
 264                         $filesystem->dumpFile($this->output
, $content); 
 265                 } catch (IOExceptionInterface 
$e) { 
 267                         throw new Error(sprintf('Unable to write to: %s', $this->output
), $token->getLine(), $stream->getSourceContext(), $e); 
 270                 //Set name in context key 
 271                 $ref = new AssignNameExpression($this->token
, $token->getLine()); 
 273                 //Set output in context value 
 274                 $value = new TextNode($outputUrl, $token->getLine()); 
 276                 //Send body with context set 
 278                         //This define name in twig template by prepending $context['<name>'] = '<output>'; 
 279                         new SetNode(true, $ref, $value, $token->getLine(), $this->getTag()), 
 280                         //The tag captured body 
 288          * @param Token $token The \Twig\Token instance 
 289          * @return bool The token end test result 
 291         public function testEndTag(Token 
$token): bool { 
 292                 return $token->test(['end'.$this->getTag()]); 
 296          * Get path from bundled file 
 298          * @see https://symfony.com/doc/current/bundles.html#overridding-the-bundle-directory-structure 
 300          * @param string $file The bundled file path 
 301          * @param int $lineno The template line where the error occurred 
 302          * @param Source $source The source context where the error occurred 
 303          * @param Exception $prev The previous exception 
 304          * @return string The resolved file path 
 306         public function getLocated(string $file, int $lineno = 0, ?Source 
$source = null, ?\Exception 
$prev = null): string { 
 307                 /*TODO: add a @jquery magic feature ? 
 308                 if ($file == '@jquery') { 
 309                         #header('Content-Type: text/plain'); 
 312                         return $this->config['jquery']; 
 315                 //Check that we have a / separator between bundle name and path 
 316                 if (($pos = strpos($file, '/')) === false) { 
 317                         throw new Error(sprintf('Invalid path "%s"', $file), $lineno, $source); 
 321                 $bundle = substr($file, 0, $pos); 
 324                 $path = substr($file, $pos + 
1); 
 326                 //Check for bundle suffix presence 
 327                 //XXX: use "bundle templates automatic namespace" mimicked behaviour to find intended bundle and/or path 
 328                 //XXX: see https://symfony.com/doc/4.3/templates.html#bundle-templates 
 329                 if (strlen($bundle) < strlen('Bundle') || substr($bundle, -strlen('Bundle')) !== 'Bundle') { 
 330                         //Append Bundle in an attempt to fix it's naming for locator 
 333                         //Check for public resource prefix presence 
 334                         if (strlen($path) < strlen('Resources/public') || substr($path, 0, strlen('Resources/public')) != 'Resources/public') { 
 335                                 //Prepend standard public path 
 336                                 $path = 'Resources/public/'.$path; 
 340                 //Resolve bundle prefix 
 342                         $prefix = $this->locator
->locate($bundle); 
 343                 //Catch bundle does not exist or is not enabled exception 
 344                 } catch(\InvalidArgumentException 
$e) { 
 345                         //Fix lowercase first bundle character 
 346                         if ($bundle[1] > 'Z' || $bundle[1] < 'A') { 
 347                                 $bundle[1] = strtoupper($bundle[1]); 
 350                         //Detect double bundle suffix 
 351                         if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') { 
 353                                 $bundle = substr($bundle, 0, -strlen('Bundle')); 
 356                         //Convert snake case in camel case 
 357                         if (strpos($bundle, '_') !== false) { 
 358                                 //Fix every first character following a _ 
 359                                 while(($cur = strpos($bundle, '_')) !== false) { 
 360                                         $bundle = substr($bundle, 0, $cur).ucfirst(substr($bundle, $cur + 
1)); 
 364                         //Resolve fixed bundle prefix 
 366                                 $prefix = $this->locator
->locate($bundle); 
 367                                 //Catch bundle does not exist or is not enabled exception again 
 368                         } catch(\InvalidArgumentException 
$e) { 
 369                                 //Bail out as bundle or path is invalid and we have no way to know what was meant 
 370                                 throw new Error(sprintf('Invalid bundle name "%s" in path "%s". Maybe you meant "%s"', substr($file, 1, $pos - 1), $file, $bundle.'/'.$path), $lineno, $source, $e); 
 374                 //Return solved bundle prefix and path 
 375                 return $prefix.$path;