2 // src/Rapsys/PackBundle/Twig/PackTokenParser.php 
   3 namespace Rapsys\PackBundle\Twig
; 
   5 use Symfony\Component\HttpKernel\Config\FileLocator
; 
   6 use Symfony\Component\DependencyInjection\ContainerInterface
; 
   7 use Symfony\Component\Asset\Packages
; 
   9 class PackTokenParser 
extends \Twig_TokenParser 
{ 
  15          * @param class         $fileLocator            The FileLocator instance 
  16          * @param class         $containerInterface     The Container Interface instance 
  17          * @param class         $assetsPackages         The Assets Packages instance 
  18          * @param string        $prefix                 The prefix path 
  19          * @param string        $tag                    The tag name 
  20          * @param string        $output                 The default output string 
  21          * @param array         $filters                The default filters array 
  23         public function __construct(FileLocator 
$fileLocator, ContainerInterface 
$containerInterface, Packages 
$assetsPackages, $prefix, $tag, $output, $filters) { 
  24                 $this->fileLocator              
= $fileLocator; 
  25                 $this->containerInterface       
= $containerInterface; 
  26                 $this->assetsPackages           
= $assetsPackages; 
  27                 $this->prefix                   
= $prefix; 
  29                 $this->output                   
= $output; 
  30                 $this->filters                  
= $filters; 
  32                 if ($this->containerInterface
->hasParameter('rapsys_pack')) { 
  33                         if ($parameters = $this->containerInterface
->getParameter('rapsys_pack')) { 
  34                                 if (isset($parameters['timeout'])) { 
  35                                         $timeout = $parameters['timeout']; 
  36                                 } elseif (isset($parameters['agent'])) { 
  37                                         $userAgent = $parameters['agent']; 
  38                                 } elseif (isset($parameters['redirect'])) { 
  39                                         $redirect = $parameters['redirect']; 
  44                 //Set http default timeout 
  45                 $this->timeout 
= ini_get('default_socket_timeout'); 
  46                 //Set http default user agent 
  47                 $this->userAgent 
= ini_get('user_agent'); 
  48                 //Set http default redirect 
  51                 //Try to load service defaults 
  52                 if ($this->containerInterface
->hasParameter('rapsys_pack')) { 
  53                         if ($parameters = $this->containerInterface
->getParameter('rapsys_pack')) { 
  54                                 if (!empty($parameters['timeout'])) { 
  55                                         $this->timeout 
= $parameters['timeout']; 
  57                                 if (!empty($parameters['agent'])) { 
  58                                         $this->userAgent 
= $parameters['agent']; 
  60                                 if (!empty($parameters['redirect'])) { 
  61                                         $this->redirect 
= $parameters['redirect']; 
  67         public function getTag() { 
  71         public function parse(\Twig_Token 
$token) { 
  72                 $parser = $this->parser
; 
  73                 $stream = $this->parser
->getStream(); 
  77                 $output = $this->output
; 
  78                 $filters = $this->filters
; 
  82                 while (!$stream->test(\Twig_Token
::BLOCK_END_TYPE
)) { 
  83                         if ($stream->test(\Twig_Token
::STRING_TYPE
)) { 
  84                                 // '@jquery', 'js/src/core/*', 'js/src/extra.js' 
  85                                 $inputs[] = $stream->next()->getValue(); 
  86                         } elseif ($stream->test(\Twig_Token
::NAME_TYPE
, 'filter')) { 
  89                                 $stream->expect(\Twig_Token
::OPERATOR_TYPE
, '='); 
  90                                 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(\Twig_Token
::STRING_TYPE
)->getValue())))); 
  91                         } elseif ($stream->test(\Twig_Token
::NAME_TYPE
, 'output')) { 
  92                                 // output='js/packed/*.js' OR output='js/core.js' 
  94                                 $stream->expect(\Twig_Token
::OPERATOR_TYPE
, '='); 
  95                                 $output = $stream->expect(\Twig_Token
::STRING_TYPE
)->getValue(); 
  96                         } elseif ($stream->test(\Twig_Token
::NAME_TYPE
, 'name')) { 
  99                                 $stream->expect(\Twig_Token
::OPERATOR_TYPE
, '='); 
 100                                 $name = $stream->expect(\Twig_Token
::STRING_TYPE
)->getValue(); 
 102                                 $token = $stream->getCurrent(); 
 103                                 throw new \
Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', \Twig_Token
::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext()); 
 107                 $stream->expect(\Twig_Token
::BLOCK_END_TYPE
); 
 109                 $body = $this->parser
->subparse(array($this, 'testEndTag'), true); 
 111                 $stream->expect(\Twig_Token
::BLOCK_END_TYPE
); 
 113                 //Replace star with sha1 
 114                 if (($pos = strpos($output, '*')) !== false) { 
 115                         #XXX: assetic code: substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7) 
 116                         $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 
1); 
 120                 for($k = 0; $k < count($inputs); $k++
) { 
 121                         //Deal with generic url 
 122                         if (strpos($inputs[$k], '//') === 0) { 
 124                                 $scheme = 'https://'; 
 125                                 //Try to load service scheme 
 126                                 if ($this->containerInterface
->hasParameter('rapsys_pack')) { 
 127                                         if ($parameters = $this->containerInterface
->getParameter('rapsys_pack')) { 
 128                                                 if (isset($parameters['scheme'])) { 
 129                                                         $scheme = $parameters['scheme']; 
 134                                 $inputs[$k] = $scheme.substr($inputs[$k], 2); 
 135                         //Deal with non url path 
 136                         } elseif (strpos($inputs[$k], '://') === false) { 
 137                                 //Check if we have a bundle path 
 138                                 if ($inputs[$k][0] == '@') { 
 139                                         //Check that we don't have only a path 
 140                                         if (($pos = strpos($inputs[$k], '/')) === false) { 
 141                                                 #TODO: @jquery support (if we really want it) 
 142                                                 #header('Content-Type: text/plain'); 
 144                                                 #if ($inputs[0] == '@jquery') { 
 147                                                 throw new \
Twig_Error_Syntax(sprintf('Invalid input path "%s"', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 149                                         //Resolve bundle prefix 
 150                                         $inputs[$k] = $this->fileLocator
->locate(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 
1); 
 153                                 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) { 
 155                                         $replacement = glob($inputs[$k], GLOB_NOSORT
|GLOB_BRACE
); 
 156                                         //Check that these are working files 
 157                                         foreach($replacement as $input) { 
 158                                                 if (!is_file($input)) { 
 159                                                         throw new \
Twig_Error_Syntax(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 162                                         //Replace with glob path 
 163                                         array_splice($inputs, $k, 1, $replacement); 
 165                                         $k +
= count($replacement) - 1; 
 166                                 //Check that it's a file 
 167                                 } elseif (!is_file($inputs[$k])) { 
 168                                         throw new \
Twig_Error_Syntax(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext()); 
 174                 $ctx = stream_context_create( 
 177                                         'timeout' => $this->timeout
, 
 178                                         'user_agent' => $this->userAgent
, 
 179                                         'redirect' => $this->redirect
, 
 185                 if (!empty($inputs)) { 
 186                         //Retrieve files content 
 187                         foreach($inputs as $input) { 
 188                                 //Try to retrieve content 
 189                                 if (($data = file_get_contents($input, false, $ctx)) === false) { 
 190                                         throw new \
Twig_Error_Syntax(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext()); 
 196                         #TODO: trigger error about empty inputs ? 
 200                 if (!empty($filters)) { 
 202                         foreach($filters as $filter) { 
 204                                 #$filter = __NAMESPACE__.'\\Filter\\'.$filter; 
 206                                 $tool = new $filter($this->containerInterface
, $stream->getSourceContext(), $token->getLine()); 
 208                                 $content = $tool->process($content); 
 213                         #TODO: trigger error about empty filters ? 
 216                 //Create output dir on demand 
 217                 if (!is_dir($parent = $dir = dirname($this->prefix
.$output))) { 
 219                                 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755) 
 220                                 mkdir($dir, 0777, true); 
 221                         } catch (\Exception 
$e) { 
 222                                 throw new \
Twig_Error_Syntax(sprintf('Unable to create directory: %s', $dir), $token->getLine(), $stream->getSourceContext()); 
 227                 //XXX: atomic rotation is required to avoid partial content in reverse cache 
 228                 if (file_put_contents($this->prefix
.$output.'.new', $content) === false) { 
 229                         throw new \
Twig_Error_Syntax(sprintf('Unable to write to: %s', $prefix.$output.'.new'), $token->getLine(), $stream->getSourceContext()); 
 233                 if (is_file($this->prefix
.$output) && unlink($this->prefix
.$output) === false) { 
 234                         throw new \
Twig_Error_Syntax(sprintf('Unable to unlink: %s', $prefix.$output), $token->getLine(), $stream->getSourceContext()); 
 238                 if (rename($this->prefix
.$output.'.new', $this->prefix
.$output) === false) { 
 239                         throw new \
Twig_Error_Syntax(sprintf('Unable to rename: %s to %s', $prefix.$output.'.new', $prefix.$output), $token->getLine(), $stream->getSourceContext()); 
 243                 //XXX: was next line to support module specific asset configuration 
 244                 #if (($output = $this->assetsPackages->getUrl($output, 'rapsys_pack')) === false) { 
 245                 if (($output = $this->assetsPackages
->getUrl($output)) === false) { 
 246                         throw new \
Twig_Error_Syntax(sprintf('Unable to get url for asset: %s with package %s', $output, 'rapsys_pack'), $token->getLine(), $stream->getSourceContext()); 
 250                 return new PackNode(array('value' => $body), array('inputs' => $inputs, 'filters' => $filters, 'name' => $name, 'output' => $output), $token->getLine(), $this->getTag()); 
 253         public function testEndTag(\Twig_Token 
$token) { 
 254                 return $token->test(array('end'.$this->getTag()));