]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/PackTokenParser.php
Cleanup and add features to implement
[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 //TODO: support @jquery ? or is it supported already with fileLocator->locate ?
84 for($k = 0; $k < count($inputs); $k++) {
85 //Deal with generic url
86 if (strpos($inputs[$k], '//') === 0) {
87 //TODO: set this as a parameter (scheme)
88 #if ($containerInterface->hasParameter('rapsys_pack.default_scheme')) {
89 # if ($parameters = $containerInterface->getParameter('rapsys_pack.default_scheme')) {
90 $inputs[$k] = 'https:'.$inputs[$k];
91 //Deal with non url path
92 } elseif (strpos($inputs[$k], '://') === false) {
93 //Check if we have a bundle path
94 if ($inputs[$k][0] == '@') {
95 if (($pos = strpos($inputs[$k], '/')) === false) {
96 throw new \Twig_Error_Syntax(sprintf('Invalid input path "%s"', $inputs[$k]), $token->getLine(), $stream->getFilename());
97 }
98 //Extract prefix
99 #$inputs[$k] = $this->kernel->locateResource(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 1);
100 $inputs[$k] = $this->fileLocator->locate(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 1);
101 }
102 //Deal with globs
103 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
104 //Get replacement
105 $replacement = glob($inputs[$k], GLOB_NOSORT|GLOB_BRACE);
106 //Check that these are working files
107 foreach($replacement as $input) {
108 if (!is_file($input)) {
109 throw new \Twig_Error_Syntax(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getFilename());
110 }
111 }
112 //Replace with glob path
113 array_splice($inputs, $k, 1, $replacement);
114 //Fix current key
115 $k += count($replacement) - 1;
116 //Check that it's a file
117 } elseif (!is_file($inputs[$k])) {
118 throw new \Twig_Error_Syntax(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getFilename());
119 }
120 }
121 }
122
123 //Retrieve files content
124 foreach($inputs as $input) {
125 //Set timeout
126 $ctx = stream_context_create(
127 array(
128 'http' => array(
129 //TODO: set this as a parameter (scheme)
130 #if ($containerInterface->hasParameter('rapsys_pack.input_timeout')) {
131 # if ($parameters = $containerInterface->getParameter('rapsys_pack.input_timeout')) {
132 'timeout' => 5
133 )
134 )
135 );
136 //Try to retrieve content
137 if (($data = file_get_contents($input, false, $ctx)) === false) {
138 throw new \Twig_Error_Syntax(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getFilename());
139 }
140 //Append content
141 $content .= $data;
142 }
143
144 //Use tool
145 if (!empty($this->tool) && is_executable($this->tool)) {
146 $descriptorSpec = array(
147 0 => array('pipe', 'r'),
148 1 => array('pipe', 'w'),
149 2 => array('pipe', 'w')
150 );
151 if (is_resource($proc = proc_open($this->tool, $descriptorSpec, $pipes))) {
152 //Set stderr as non blocking
153 stream_set_blocking($pipes[2], 0);
154 //Send content to stdin
155 fwrite($pipes[0], $content);
156 //Close stdin
157 fclose($pipes[0]);
158 //Read content from stdout
159 if ($stdout = stream_get_contents($pipes[1])) {
160 $content = $stdout;
161 }
162 //Close stdout
163 fclose($pipes[1]);
164 //Read content from stderr
165 if ($stderr = stream_get_contents($pipes[2])) {
166 throw new \Twig_Error_Syntax(sprintf('Got unexpected strerr for %s: %s', $this->tool, $stderr), $token->getLine(), $stream->getFilename());
167 }
168 //Close stderr
169 fclose($pipes[2]);
170 //Close process
171 if ($ret = proc_close($proc)) {
172 throw new \Twig_Error_Syntax(sprintf('Got unexpected non zero return code %s: %d', $this->tool, $ret), $token->getLine(), $stream->getFilename());
173 }
174 }
175 }
176
177 //Create output dir on demand
178 if (!is_dir($parent = $dir = dirname($this->prefix.$output))) {
179 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755)
180 mkdir($dir, 0777, true);
181 }
182
183 //Send file content
184 //TODO: see if atomic rotation is really necessary ?
185 //XXX: version management is done via rapsys_pack configuration atomic should be useless
186 //TODO: implement asset versionning or re-use internal functions
187 if (file_put_contents($this->prefix.$output.'.new', $content) === false) {
188 throw new \Twig_Error_Syntax(sprintf('Unable to write to: %s', $prefix.$output.'.new'), $token->getLine(), $stream->getFilename());
189 }
190
191 //Remove old file
192 if (is_file($this->prefix.$output) && unlink($this->prefix.$output) === false) {
193 throw new \Twig_Error_Syntax(sprintf('Unable to unlink: %s', $prefix.$output), $token->getLine(), $stream->getFilename());
194 }
195
196 //Rename it
197 if (rename($this->prefix.$output.'.new', $this->prefix.$output) === false) {
198 throw new \Twig_Error_Syntax(sprintf('Unable to rename: %s to %s', $prefix.$output.'.new', $prefix.$output), $token->getLine(), $stream->getFilename());
199 }
200
201 //Retrieve asset uri
202 if (($output = $this->containerInterface->get('assets.packages')->getUrl($output, 'rapsys_pack')) === false) {
203 throw new \Twig_Error_Syntax(sprintf('Unable to get url for asset: %s with package %s', $output, 'rapsys_pack'), $token->getLine(), $stream->getFilename());
204 }
205
206 //Send pack node
207 return new PackNode(array('value' => $body), array('inputs' => $inputs, 'filters' => $filters, 'name' => $name, 'output' => $output), $token->getLine(), $this->getTag());
208 }
209
210 public function testEndTag(\Twig_Token $token) {
211 return $token->test(array('end'.$this->getTag()));
212 }
213 }