]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/PackTokenParser.php
8218ee1a1a9fe3c2bec4a0aaa4ade0f7f4db1188
[packbundle] / Twig / PackTokenParser.php
1 <?php
2 // src/Rapsys/PackBundle/Twig/PackTokenParser.php
3 namespace Rapsys\PackBundle\Twig;
4
5 use Symfony\Component\HttpKernel\Config\FileLocator;
6 use Symfony\Component\DependencyInjection\ContainerInterface;
7
8 class PackTokenParser extends \Twig_TokenParser {
9 private $tag;
10
11 /**
12 * Constructor.
13 *
14 * @param class $fileLocator The FileLocator instance
15 * @param class $assetsPackages The Assets Packages instance
16 * @param string $prefix The prefix path
17 * @param string $tag The tag name
18 * @param string $output The default output string
19 * @param string $tool The tool path
20 */
21 public function __construct(FileLocator $fileLocator, ContainerInterface $containerInterface, $prefix, $tag, $output, $tool = null) {
22 $this->fileLocator = $fileLocator;
23 $this->containerInterface = $containerInterface;
24 $this->prefix = $prefix;
25 $this->tag = $tag;
26 $this->output = $output;
27 $this->tool = $tool;
28 }
29
30 public function getTag() {
31 return $this->tag;
32 }
33
34 public function parse(\Twig_Token $token) {
35 $parser = $this->parser;
36 $stream = $this->parser->getStream();
37
38 $inputs = array();
39 $filters = array();
40 $name = 'asset_url';
41 $output = $this->output;
42
43 $content = '';
44
45 while (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
46 if ($stream->test(\Twig_Token::STRING_TYPE)) {
47 // '@jquery', 'js/src/core/*', 'js/src/extra.js'
48 $inputs[] = $stream->next()->getValue();
49 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'filter')) {
50 // filter='yui_js'
51 $stream->next();
52 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
53 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(\Twig_Token::STRING_TYPE)->getValue()))));
54 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'output')) {
55 // output='js/packed/*.js' OR output='js/core.js'
56 $stream->next();
57 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
58 $output = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
59 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'name')) {
60 // name='core_js'
61 $stream->next();
62 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
63 $name = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
64 } else {
65 $token = $stream->getCurrent();
66 throw new \Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', \Twig_Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getFilename());
67 }
68 }
69
70 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
71
72 $body = $this->parser->subparse(array($this, 'testEndTag'), true);
73
74 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
75
76 //Replace star with sha1
77 if (($pos = strpos($output, '*')) !== false) {
78 #XXX: assetic code : substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7)
79 $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 1);
80 }
81
82 //Deal with inputs
83 for($k = 0; $k < count($inputs); $k++) {
84 //Deal with generic url
85 if (strpos($inputs[$k], '//') === 0) {
86 //TODO: set this as a parameter (scheme)
87 $inputs[$k] = 'https:'.$inputs[$k];
88 //Deal with non url path
89 } elseif (strpos($inputs[$k], '://') === false) {
90 //Check if we have a bundle path
91 if ($inputs[$k][0] == '@') {
92 if (($pos = strpos($inputs[$k], '/')) === false) {
93 throw new \Twig_Error_Syntax(sprintf('Invalid input path "%s"', $inputs[$k]), $token->getLine(), $stream->getFilename());
94 }
95 //Extract prefix
96 #$inputs[$k] = $this->kernel->locateResource(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 1);
97 $inputs[$k] = $this->fileLocator->locate(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 1);
98 }
99 //Deal with globs
100 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
101 //Get replacement
102 $replacement = glob($inputs[$k], GLOB_NOSORT|GLOB_BRACE);
103 //Check that these are working files
104 foreach($replacement as $input) {
105 if (!is_file($input)) {
106 throw new \Twig_Error_Syntax(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getFilename());
107 }
108 }
109 //Replace with glob path
110 array_splice($inputs, $k, 1, $replacement);
111 //Fix current key
112 $k += count($replacement) - 1;
113 //Check that it's a file
114 } elseif (!is_file($inputs[$k])) {
115 throw new \Twig_Error_Syntax(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getFilename());
116 }
117 }
118 }
119
120 //Retrieve files content
121 foreach($inputs as $input) {
122 //Set timeout
123 $ctx = stream_context_create(
124 array(
125 'http' => array(
126 'timeout' => 5
127 )
128 )
129 );
130 //Try to retrieve content
131 if (($data = file_get_contents($input, false, $ctx)) === false) {
132 throw new \Twig_Error_Syntax(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getFilename());
133 }
134 //Append content
135 $content .= $data;
136 }
137
138 //Use tool
139 if (!empty($this->tool) && is_executable($this->tool)) {
140 $descriptorSpec = array(
141 0 => array('pipe', 'r'),
142 1 => array('pipe', 'w'),
143 2 => array('pipe', 'w')
144 );
145 if (is_resource($proc = proc_open($this->tool, $descriptorSpec, $pipes))) {
146 //Set stderr as non blocking
147 stream_set_blocking($pipes[2], 0);
148 //Send content to stdin
149 fwrite($pipes[0], $content);
150 //Close stdin
151 fclose($pipes[0]);
152 //Read content from stdout
153 if ($stdout = stream_get_contents($pipes[1])) {
154 $content = $stdout;
155 }
156 //Close stdout
157 fclose($pipes[1]);
158 //Read content from stderr
159 if ($stderr = stream_get_contents($pipes[2])) {
160 throw new \Twig_Error_Syntax(sprintf('Got unexpected strerr for %s: %s', $this->tool, $stderr), $token->getLine(), $stream->getFilename());
161 }
162 //Close stderr
163 fclose($pipes[2]);
164 //Close process
165 if ($ret = proc_close($proc)) {
166 throw new \Twig_Error_Syntax(sprintf('Got unexpected non zero return code %s: %d', $this->tool, $ret), $token->getLine(), $stream->getFilename());
167 }
168 }
169 }
170
171 //Create output dir on demand
172 if (!is_dir($parent = $dir = dirname($this->prefix.$output))) {
173 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755)
174 mkdir($dir, 0777, true);
175 }
176
177 //Send file content
178 //TODO: see if atomic rotation is really necessary ?
179 //XXX: version management is done via rapsys_pack configuration atomic should be useless
180 //TODO: implement asset versionning or re-use internal functions
181 if (file_put_contents($this->prefix.$output.'.new', $content) === false) {
182 throw new \Twig_Error_Syntax(sprintf('Unable to write to: %s', $prefix.$output.'.new'), $token->getLine(), $stream->getFilename());
183 }
184
185 //Remove old file
186 if (is_file($this->prefix.$output) && unlink($this->prefix.$output) === false) {
187 throw new \Twig_Error_Syntax(sprintf('Unable to unlink: %s', $prefix.$output), $token->getLine(), $stream->getFilename());
188 }
189
190 //Rename it
191 if (rename($this->prefix.$output.'.new', $this->prefix.$output) === false) {
192 throw new \Twig_Error_Syntax(sprintf('Unable to rename: %s to %s', $prefix.$output.'.new', $prefix.$output), $token->getLine(), $stream->getFilename());
193 }
194
195 //Retrieve asset uri
196 if (($output = $this->containerInterface->get('assets.packages')->getUrl($output, 'rapsys_pack')) === false) {
197 throw new \Twig_Error_Syntax(sprintf('Unable to get url for asset: %s with package %s', $output, 'rapsys_pack'), $token->getLine(), $stream->getFilename());
198 }
199
200 //Send pack node
201 return new PackNode(array('value' => $body), array('inputs' => $inputs, 'filters' => $filters, 'name' => $name, 'output' => $output), $token->getLine(), $this->getTag());
202 }
203
204 public function testEndTag(\Twig_Token $token) {
205 return $token->test(array('end'.$this->getTag()));
206 }
207 }