3 namespace Rapsys\PackBundle\Twig
; 
   5 use Symfony\Component\HttpKernel\Config\FileLocator
; 
   6 use Symfony\Component\Asset\PackageInterface
; 
   7 use Twig\Error\RuntimeError
; 
   8 use Twig\Error\SyntaxError
; 
   9 use Twig\Node\Expression\AssignNameExpression
; 
  11 use Twig\Node\SetNode
; 
  12 use Twig\Node\TextNode
; 
  14 use Twig\TokenParser\AbstractTokenParser
; 
  16 class PackTokenParser 
extends AbstractTokenParser 
{ 
  23          * @param class         $locator        The FileLocator instance 
  24          * @param class         $package        The Assets Package instance 
  25          * @param string        $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         public function getTag() { 
  72          * @param class $token The \Twig\Token instance 
  74          * @return class The PackNode 
  76          * @todo see if we can't add a debug mode behaviour 
  78          * If twig.debug or env=dev (or rapsys_pack.config.debug?) is set, it should be possible to loop on each input 
  79          * and process the captured body without applying requested filter. 
  83          * - retrieve fixe link from input s%@(Name)Bundle/Resources/public(/somewhere/file.ext)%/bundles/\L\1\E\2% 
  85          *   - generate a set asset_url=x 
  88         public function parse(Token 
$token) { 
  89                 $parser = $this->parser
; 
  90                 $stream = $this->parser
->getStream(); 
  94                 $output = $this->output
; 
  95                 $filters = $this->filters
; 
  99                 //Process the token block until end 
 100                 while (!$stream->test(Token
::BLOCK_END_TYPE
)) { 
 101                         //The files to process 
 102                         if ($stream->test(Token
::STRING_TYPE
)) { 
 103                                 //'somewhere/somefile.(css,img,js)' 'somewhere/*' '@jquery' 
 104                                 $inputs[] = $stream->next()->getValue(); 
 106                         } elseif ($stream->test(Token
::NAME_TYPE
, 'filters')) { 
 109                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 110                                 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(Token
::STRING_TYPE
)->getValue())))); 
 112                         } elseif ($stream->test(Token
::NAME_TYPE
, 'output')) { 
 113                                 //output='js/packed/*.js' OR output='js/core.js' 
 115                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 116                                 $output = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 118                         } elseif ($stream->test(Token
::NAME_TYPE
, 'name')) { 
 121                                 $stream->expect(Token
::OPERATOR_TYPE
, '='); 
 122                                 $name = $stream->expect(Token
::STRING_TYPE
)->getValue(); 
 125                                 $token = $stream->getCurrent(); 
 126                                 throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s"', Token
::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext()); 
 131                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 134                 $body = $this->parser
->subparse([$this, 'testEndTag'], true); 
 137                 $stream->expect(Token
::BLOCK_END_TYPE
); 
 139                 //TODO: debug mode should be inserted here before the output variable is rewritten 
 141                 //Replace star with sha1 
 142                 if (($pos = strpos($output, '*')) !== false) { 
 143                         //XXX: assetic use substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7) 
 144                         $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 
1); 
 148                 for($k = 0; $k < count($inputs); $k++
) { 
 149                         //Deal with generic url 
 150                         if (strpos($inputs[$k], '//') === 0) { 
 152                                 $inputs[$k] = $this->scheme
.substr($inputs[$k], 2); 
 153                         //Deal with non url path 
 154                         } elseif (strpos($inputs[$k], '://') === false) { 
 155                                 //Check if we have a bundle path 
 156                                 if ($inputs[$k][0] == '@') { 
 157                                         //Check that we have a / separator between bundle name and path 
 158                                         if (($pos = strpos($inputs[$k], '/')) === false) { 
 159                                                 //TODO: add a @jquery magic feature ? 
 161                                                 header('Content-Type: text/plain'); 
 163                                                 if ($inputs[0] == '@jquery') { 
 167                                                 throw new RuntimeError(sprintf('Invalid input path "%s"', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 169                                         //Resolve bundle prefix 
 170                                         $inputs[$k] = $this->locator
->locate(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 
1); 
 173                                 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) { 
 175                                         $replacement = glob($inputs[$k], GLOB_NOSORT
|GLOB_BRACE
); 
 176                                         //Check that these are working files 
 177                                         foreach($replacement as $input) { 
 178                                                 //Check that it's a file 
 179                                                 if (!is_file($input)) { 
 180                                                         throw new RuntimeError(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 183                                         //Replace with glob path 
 184                                         array_splice($inputs, $k, 1, $replacement); 
 186                                         $k +
= count($replacement) - 1; 
 187                                 //Check that it's a file 
 188                                 } elseif (!is_file($inputs[$k])) { 
 189                                         throw new RuntimeError(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 195                 $ctx = stream_context_create( 
 198                                         'timeout' => $this->timeout
, 
 199                                         'user_agent' => $this->agent
, 
 200                                         'redirect' => $this->redirect
, 
 206                 if (!empty($inputs)) { 
 207                         //Retrieve files content 
 208                         foreach($inputs as $input) { 
 209                                 //Try to retrieve content 
 210                                 if (($data = file_get_contents($input, false, $ctx)) === false) { 
 211                                         throw new RuntimeError(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext()); 
 217                         //Trigger error about empty inputs 
 218                         //XXX: There may be a legitimate case where inputs is empty, if so please contact the author 
 219                         throw new RuntimeError('Empty inputs token', $token->getLine(), $stream->getSourceContext()); 
 223                 if (!empty($filters)) { 
 225                         foreach($filters as $filter) { 
 227                                 $args = [$stream->getSourceContext(), $token->getLine()]; 
 228                                 //Check if args is available 
 229                                 if (!empty($filter['args'])) { 
 230                                         //Append args if provided 
 231                                         $args +
= $filter['args']; 
 234                                 $reflection = new \
ReflectionClass($filter['class']); 
 236                                 $tool = $reflection->newInstanceArgs($args); 
 238                                 $content = $tool->process($content); 
 240                                 unset($tool, $reflection); 
 243                         //Trigger error about empty filters 
 244                         //XXX: There may be a legitimate case where filters is empty, if so please contact the author 
 245                         throw new RuntimeError('Empty filters token', $token->getLine(), $stream->getSourceContext()); 
 249                 //XXX: this path is the merge of services.assets.path_package.arguments[0] and rapsys_pack.output.(css,img,js) 
 250                 if (($outputUrl = $this->package
->getUrl($output)) === false) { 
 251                         throw new RuntimeError(sprintf('Unable to get url for asset: %s', $output), $token->getLine(), $stream->getSourceContext()); 
 254                 //Check if we have a bundle path 
 255                 if ($output[0] == '@') { 
 256                         //Check that we have a / separator between bundle name and path 
 257                         if (($pos = strpos($output, '/')) === false) { 
 258                                 throw new RuntimeError(sprintf('Invalid output path "%s"', $output), $token->getLine(), $stream->getSourceContext()); 
 260                         //Resolve bundle prefix 
 261                         $output = $this->locator
->locate(substr($output, 0, $pos)).substr($output, $pos + 
1); 
 264                 //Create output dir if not present 
 265                 if (!is_dir($dir = dirname($output))) { 
 267                                 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755) 
 268                                 mkdir($dir, 0777, true); 
 269                         } catch (\Exception 
$e) { 
 270                                 throw new RuntimeError(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext()); 
 275                 //XXX: to avoid partial content in reverse cache we use atomic rotation write, unlink and move 
 277                         if (file_put_contents($output.'.new', $content) === false) { 
 278                                 throw new \
Exception(); 
 280                 } catch(\Exception 
$e) { 
 281                         throw new RuntimeError(sprintf('Unable to write to: %s', $output.'.new'), $token->getLine(), $stream->getSourceContext()); 
 285                 if (is_file($output)) { 
 287                                 if (unlink($output) === false) { 
 288                                         throw new \
Exception(); 
 290                         } catch (\Exception 
$e) { 
 291                                 throw new RuntimeError(sprintf('Unable to unlink: %s', $output), $token->getLine(), $stream->getSourceContext()); 
 297                         if (rename($output.'.new', $output) === false) { 
 298                                         throw new \
Exception(); 
 300                 } catch (\Exception 
$e) { 
 301                         throw new RuntimeError(sprintf('Unable to rename: %s to %s', $output.'.new', $output), $token->getLine(), $stream->getSourceContext()); 
 304                 //Set name in context key 
 305                 $ref = new AssignNameExpression($name, $token->getLine()); 
 307                 //Set output in context value 
 308                 $value = new TextNode($outputUrl, $token->getLine()); 
 310                 //Send body with context set 
 312                         //This define name in twig template by prepending $context['<name>'] = '<output>'; 
 313                         new SetNode(true, $ref, $value, $token->getLine(), $this->getTag()), 
 314                         //The tag captured body 
 322          * @param class $token The \Twig\Token instance 
 326         public function testEndTag(Token 
$token) { 
 327                 return $token->test(['end'.$this->getTag()]);