]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/PackTokenParser.php
Add twig classes uses
[packbundle] / Twig / PackTokenParser.php
1 <?php
2
3 namespace Rapsys\PackBundle\Twig;
4
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;
10 use Twig\Node\Node;
11 use Twig\Node\SetNode;
12 use Twig\Node\TextNode;
13 use Twig\Token;
14 use Twig\TokenParser\AbstractTokenParser;
15
16 class PackTokenParser extends AbstractTokenParser {
17 //The tag name
18 private $tag;
19
20 /**
21 * Constructor
22 *
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
29 */
30 public function __construct(FileLocator $locator, PackageInterface $package, $config, $tag, $output, $filters) {
31 //Save locator
32 $this->locator = $locator;
33
34 //Save assets package
35 $this->package = $package;
36
37 //Set name
38 $this->name = $config['name'];
39
40 //Set scheme
41 $this->scheme = $config['scheme'];
42
43 //Set timeout
44 $this->timeout = $config['timeout'];
45
46 //Set agent
47 $this->agent = $config['agent'];
48
49 //Set redirect
50 $this->redirect = $config['redirect'];
51
52 //Set tag
53 $this->tag = $tag;
54
55 //Set output
56 $this->output = $output;
57
58 //Set filters
59 $this->filters = $filters;
60 }
61
62 /**
63 * Get the tag name
64 */
65 public function getTag() {
66 return $this->tag;
67 }
68
69 /**
70 * Parse the token
71 *
72 * @param class $token The \Twig\Token instance
73 *
74 * @return class The PackNode
75 *
76 * @todo see if we can't add a debug mode behaviour
77 *
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.
80 *
81 * @todo list:
82 * - detect debug mode
83 * - retrieve fixe link from input s%@(Name)Bundle/Resources/public(/somewhere/file.ext)%/bundles/\L\1\E\2%
84 * - for each inputs:
85 * - generate a set asset_url=x
86 * - generate a body
87 */
88 public function parse(Token $token) {
89 $parser = $this->parser;
90 $stream = $this->parser->getStream();
91
92 $inputs = [];
93 $name = $this->name;
94 $output = $this->output;
95 $filters = $this->filters;
96
97 $content = '';
98
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();
105 //The filters token
106 } elseif ($stream->test(Token::NAME_TYPE, 'filters')) {
107 //filter='yui_js'
108 $stream->next();
109 $stream->expect(Token::OPERATOR_TYPE, '=');
110 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(Token::STRING_TYPE)->getValue()))));
111 //The output token
112 } elseif ($stream->test(Token::NAME_TYPE, 'output')) {
113 //output='js/packed/*.js' OR output='js/core.js'
114 $stream->next();
115 $stream->expect(Token::OPERATOR_TYPE, '=');
116 $output = $stream->expect(Token::STRING_TYPE)->getValue();
117 //The name token
118 } elseif ($stream->test(Token::NAME_TYPE, 'name')) {
119 //name='core_js'
120 $stream->next();
121 $stream->expect(Token::OPERATOR_TYPE, '=');
122 $name = $stream->expect(Token::STRING_TYPE)->getValue();
123 //Unexpected token
124 } else {
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());
127 }
128 }
129
130 //Process end block
131 $stream->expect(Token::BLOCK_END_TYPE);
132
133 //Process body
134 $body = $this->parser->subparse([$this, 'testEndTag'], true);
135
136 //Process end block
137 $stream->expect(Token::BLOCK_END_TYPE);
138
139 //TODO: debug mode should be inserted here before the output variable is rewritten
140
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);
145 }
146
147 //Process inputs
148 for($k = 0; $k < count($inputs); $k++) {
149 //Deal with generic url
150 if (strpos($inputs[$k], '//') === 0) {
151 //Fix url
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 ?
160 /*
161 header('Content-Type: text/plain');
162 var_dump($inputs);
163 if ($inputs[0] == '@jquery') {
164 exit;
165 }
166 */
167 throw new RuntimeError(sprintf('Invalid input path "%s"', $inputs[$k]), $token->getLine(), $stream->getSourceContext());
168 }
169 //Resolve bundle prefix
170 $inputs[$k] = $this->locator->locate(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 1);
171 }
172 //Deal with globs
173 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
174 //Get replacement
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());
181 }
182 }
183 //Replace with glob path
184 array_splice($inputs, $k, 1, $replacement);
185 //Fix current key
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());
190 }
191 }
192 }
193
194 //Init context
195 $ctx = stream_context_create(
196 [
197 'http' => [
198 'timeout' => $this->timeout,
199 'user_agent' => $this->agent,
200 'redirect' => $this->redirect,
201 ]
202 ]
203 );
204
205 //Check inputs
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());
212 }
213 //Append content
214 $content .= $data;
215 }
216 } else {
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());
220 }
221
222 //Check filters
223 if (!empty($filters)) {
224 //Apply all filters
225 foreach($filters as $filter) {
226 //Init args
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'];
232 }
233 //Init reflection
234 $reflection = new \ReflectionClass($filter['class']);
235 //Set instance args
236 $tool = $reflection->newInstanceArgs($args);
237 //Process content
238 $content = $tool->process($content);
239 //Remove object
240 unset($tool, $reflection);
241 }
242 } else {
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());
246 }
247
248 //Retrieve asset uri
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());
252 }
253
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());
259 }
260 //Resolve bundle prefix
261 $output = $this->locator->locate(substr($output, 0, $pos)).substr($output, $pos + 1);
262 }
263
264 //Create output dir if not present
265 if (!is_dir($dir = dirname($output))) {
266 try {
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());
271 }
272 }
273
274 //Send file content
275 //XXX: to avoid partial content in reverse cache we use atomic rotation write, unlink and move
276 try {
277 if (file_put_contents($output.'.new', $content) === false) {
278 throw new \Exception();
279 }
280 } catch(\Exception $e) {
281 throw new RuntimeError(sprintf('Unable to write to: %s', $output.'.new'), $token->getLine(), $stream->getSourceContext());
282 }
283
284 //Remove old file
285 if (is_file($output)) {
286 try {
287 if (unlink($output) === false) {
288 throw new \Exception();
289 }
290 } catch (\Exception $e) {
291 throw new RuntimeError(sprintf('Unable to unlink: %s', $output), $token->getLine(), $stream->getSourceContext());
292 }
293 }
294
295 //Rename it
296 try {
297 if (rename($output.'.new', $output) === false) {
298 throw new \Exception();
299 }
300 } catch (\Exception $e) {
301 throw new RuntimeError(sprintf('Unable to rename: %s to %s', $output.'.new', $output), $token->getLine(), $stream->getSourceContext());
302 }
303
304 //Set name in context key
305 $ref = new AssignNameExpression($name, $token->getLine());
306
307 //Set output in context value
308 $value = new TextNode($outputUrl, $token->getLine());
309
310 //Send body with context set
311 return new Node([
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
315 $body
316 ]);
317 }
318
319 /**
320 * Test for tag end
321 *
322 * @param class $token The \Twig\Token instance
323 *
324 * @return bool
325 */
326 public function testEndTag(Token $token) {
327 return $token->test(['end'.$this->getTag()]);
328 }
329 }