]> Raphaël G. Git Repositories - packbundle/blob - Parser/TokenParser.php
1115e0cdce49916b3535dc72967f034e56097d79
[packbundle] / Parser / TokenParser.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys PackBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\PackBundle\Parser;
13
14 use Symfony\Component\Asset\PackageInterface;
15 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
16 use Symfony\Component\Filesystem\Filesystem;
17 use Symfony\Component\HttpKernel\Config\FileLocator;
18
19 use Twig\Error\Error;
20 use Twig\Node\Expression\AssignNameExpression;
21 use Twig\Node\Node;
22 use Twig\Node\SetNode;
23 use Twig\Node\TextNode;
24 use Twig\Source;
25 use Twig\Token;
26 use Twig\TokenParser\AbstractTokenParser;
27
28 use Rapsys\PackBundle\RapsysPackBundle;
29
30 class TokenParser extends AbstractTokenParser {
31 /**
32 * The stream context instance
33 */
34 protected mixed $ctx;
35
36 /**
37 * Constructor
38 *
39 * @param FileLocator $locator The FileLocator instance
40 * @param PackageInterface $package The Assets Package instance
41 * @param string $token The token name
42 * @param string $tag The tag name
43 * @param string $output The default output string
44 * @param array $filters The default filter array
45 */
46 public function __construct(protected FileLocator $locator, protected PackageInterface $package, protected string $token, protected string $tag, protected string $output, protected array $filters) {
47 //Set ctx
48 $this->ctx = stream_context_create(
49 [
50 'http' => [
51 #'header' => ['Referer: https://www.openstreetmap.org/'],
52 'max_redirects' => $_ENV['RAPSYSPACK_REDIRECT'] ?? 20,
53 'timeout' => $_ENV['RAPSYSPACK_TIMEOUT'] ?? (int)ini_get('default_socket_timeout') ?: 60,
54 'user_agent' => $_ENV['RAPSYSPACK_AGENT'] ?? (($agent = ini_get('user_agent')) !== false && $agent !== "" ? (string)$agent : RapsysPackBundle::getAlias().'/'.RapsysPackBundle::getVersion())
55 ]
56 ]
57 );
58 }
59
60 /**
61 * Get the tag name
62 *
63 * @return string This tag name
64 */
65 public function getTag(): string {
66 return $this->tag;
67 }
68
69 /**
70 * Parse the token
71 *
72 * @xxx Skip filter when debug mode is enabled is not possible
73 * @xxx This code is only run once when twig cache is enabled
74 * @xxx Twig cache value is not avaible in container parameters, maybe in twig env ?
75 *
76 * @param Token $token The \Twig\Token instance
77 * @return Node The PackNode
78 */
79 public function parse(Token $token): Node {
80 //Get parser
81 $parser = $this->parser;
82
83 //Get parser stream
84 $stream = $this->parser->getStream();
85
86 //Set inputs array
87 $inputs = [];
88
89 //Set content
90 $content = '';
91
92 //Process the token block until end
93 while (!$stream->test(Token::BLOCK_END_TYPE)) {
94 //The files to process
95 if ($stream->test(Token::STRING_TYPE)) {
96 //'somewhere/somefile.(css,img,js)' 'somewhere/*' '@jquery'
97 $inputs[] = $stream->next()->getValue();
98 //The filters token
99 } elseif ($stream->test(Token::NAME_TYPE, 'filters')) {
100 //filter='yui_js'
101 $stream->next();
102 $stream->expect(Token::OPERATOR_TYPE, '=');
103 $this->filters = array_merge($this->filters, array_filter(array_map('trim', explode(',', $stream->expect(Token::STRING_TYPE)->getValue()))));
104 //The output token
105 } elseif ($stream->test(Token::NAME_TYPE, 'output')) {
106 //output='js/packed/*.js' OR output='js/core.js'
107 $stream->next();
108 $stream->expect(Token::OPERATOR_TYPE, '=');
109 $this->output = $stream->expect(Token::STRING_TYPE)->getValue();
110 //The token name
111 } elseif ($stream->test(Token::NAME_TYPE, 'token')) {
112 //name='core_js'
113 $stream->next();
114 $stream->expect(Token::OPERATOR_TYPE, '=');
115 $this->token = $stream->expect(Token::STRING_TYPE)->getValue();
116 //Unexpected token
117 } else {
118 $token = $stream->getCurrent();
119 throw new Error(sprintf('Unexpected token "%s" of value "%s"', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext());
120 }
121 }
122
123 //Process end block
124 $stream->expect(Token::BLOCK_END_TYPE);
125
126 //Process body
127 $body = $this->parser->subparse([$this, 'testEndTag'], true);
128
129 //Process end block
130 $stream->expect(Token::BLOCK_END_TYPE);
131
132 //Replace star with sha1
133 if (($pos = strpos($this->output, '*')) !== false) {
134 //XXX: assetic use substr(sha1(serialize($inputs).serialize($this->filters).serialize($this->output)), 0, 7)
135 $this->output = substr($this->output, 0, $pos).sha1(serialize($inputs).serialize($this->filters)).substr($this->output, $pos + 1);
136 }
137
138 //Process inputs
139 for($k = 0; $k < count($inputs); $k++) {
140 //Deal with generic url
141 if (strpos($inputs[$k], '//') === 0) {
142 //Fix url
143 $inputs[$k] = ($_ENV['RAPSYSPACK_SCHEME'] ?? 'https://').substr($inputs[$k], 2);
144 //Deal with non url path
145 } elseif (strpos($inputs[$k], '://') === false) {
146 //Check if we have a bundle path
147 if ($inputs[$k][0] == '@') {
148 //Resolve it
149 $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext());
150 }
151
152 //Deal with globs
153 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
154 //Get replacement
155 $replacement = glob($inputs[$k], GLOB_NOSORT|GLOB_BRACE);
156 //Check that these are working files
157 foreach($replacement as $input) {
158 //Check that it's a file
159 if (!is_file($input)) {
160 throw new Error(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext());
161 }
162 }
163 //Replace with glob path
164 array_splice($inputs, $k, 1, $replacement);
165 //Fix current key
166 $k += count($replacement) - 1;
167 //Check that it's a file
168 } elseif (!is_file($inputs[$k])) {
169 throw new Error(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext());
170 }
171 }
172 }
173
174 //Check inputs
175 if (!empty($inputs)) {
176 //Retrieve files content
177 foreach($inputs as $input) {
178 //Try to retrieve content
179 if (($data = file_get_contents($input, false, $this->ctx)) === false) {
180 throw new Error(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext());
181 }
182 //Append content
183 $content .= $data;
184 }
185 } else {
186 //Trigger error about empty inputs ?
187 //XXX: There may be a legitimate case where we want an empty file or an error, feel free to contact the author in such case
188 #throw new Error('Empty inputs token', $token->getLine(), $stream->getSourceContext());
189
190 //Send an empty node without inputs
191 return new Node();
192 }
193
194 //Check filters
195 if (!empty($this->filters)) {
196 //Apply all filters
197 foreach($this->filters as $filter) {
198 //Init args
199 $args = [$stream->getSourceContext(), $token->getLine()];
200 //Check if args is available
201 if (!empty($filter['args'])) {
202 //Append args if provided
203 $args += $filter['args'];
204 }
205 //Init reflection
206 $reflection = new \ReflectionClass($filter['class']);
207 //Set instance args
208 $tool = $reflection->newInstanceArgs($args);
209 //Process content
210 $content = $tool->process($content);
211 //Remove object
212 unset($tool, $reflection);
213 }
214 } else {
215 //Trigger error about empty filters ?
216 //XXX: There may be a legitimate case where we want only a merged file or an error, feel free to contact the author in such case
217 #throw new Error('Empty filters token', $token->getLine(), $stream->getSourceContext());
218 }
219
220 //Retrieve asset uri
221 //XXX: this path is the merge of services.assets.path_package.arguments[0] and rapsys_pack.output.(css,img,js)
222 if (($outputUrl = $this->package->getUrl($this->output)) === false) {
223 throw new Error(sprintf('Unable to get url for asset: %s', $this->output), $token->getLine(), $stream->getSourceContext());
224 }
225
226 //Check if we have a bundle path
227 if ($this->output[0] == '@') {
228 //Resolve it
229 $this->output = $this->getLocated($this->output, $token->getLine(), $stream->getSourceContext());
230 }
231
232 //Get filesystem
233 $filesystem = new Filesystem();
234
235 //Create output dir if not present
236 if (!is_dir($dir = dirname($this->output))) {
237 try {
238 //Create dir
239 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
240 $filesystem->mkdir($dir, 0775);
241 } catch (IOExceptionInterface $e) {
242 //Throw error
243 throw new Error(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext(), $e);
244 }
245 }
246
247 //Send file content
248 try {
249 //Write content to file
250 //XXX: this call is (maybe) atomic
251 //XXX: see https://symfony.com/doc/current/components/filesystem.html#dumpfile
252 $filesystem->dumpFile($this->output, $content);
253 } catch (IOExceptionInterface $e) {
254 //Throw error
255 throw new Error(sprintf('Unable to write to: %s', $this->output), $token->getLine(), $stream->getSourceContext(), $e);
256 }
257
258 //Set name in context key
259 $ref = new AssignNameExpression($this->token, $token->getLine());
260
261 //Set output in context value
262 $value = new TextNode($outputUrl, $token->getLine());
263
264 //Send body with context set
265 return new Node([
266 //This define name in twig template by prepending $context['<name>'] = '<output>';
267 new SetNode(true, $ref, $value, $token->getLine(), $this->getTag()),
268 //The tag captured body
269 $body
270 ]);
271 }
272
273 /**
274 * Test for tag end
275 *
276 * @param Token $token The \Twig\Token instance
277 * @return bool The token end test result
278 */
279 public function testEndTag(Token $token): bool {
280 return $token->test(['end'.$this->getTag()]);
281 }
282
283 /**
284 * Get path from bundled file
285 *
286 * @see https://symfony.com/doc/current/bundles.html#overridding-the-bundle-directory-structure
287 *
288 * @param string $file The bundled file path
289 * @param int $lineno The template line where the error occurred
290 * @param Source $source The source context where the error occurred
291 * @param Exception $prev The previous exception
292 * @return string The resolved file path
293 */
294 public function getLocated(string $file, int $lineno = 0, ?Source $source = null, ?\Exception $prev = null): string {
295 /*TODO: add a @jquery magic feature ?
296 if ($file == '@jquery') {
297 #header('Content-Type: text/plain');
298 #var_dump($inputs);
299 #exit;
300 return $this->config['jquery'];
301 }*/
302
303 //Check that we have a / separator between bundle name and path
304 if (($pos = strpos($file, '/')) === false) {
305 throw new Error(sprintf('Invalid path "%s"', $file), $lineno, $source);
306 }
307
308 //Set bundle
309 $bundle = substr($file, 0, $pos);
310
311 //Set path
312 $path = substr($file, $pos + 1);
313
314 //Check for bundle suffix presence
315 //XXX: use "bundle templates automatic namespace" mimicked behaviour to find intended bundle and/or path
316 //XXX: see https://symfony.com/doc/4.3/templates.html#bundle-templates
317 if (strlen($bundle) < strlen('Bundle') || substr($bundle, -strlen('Bundle')) !== 'Bundle') {
318 //Append Bundle in an attempt to fix it's naming for locator
319 $bundle .= 'Bundle';
320
321 //Check for public resource prefix presence
322 if (strlen($path) < strlen('Resources/public') || substr($path, 0, strlen('Resources/public')) != 'Resources/public') {
323 //Prepend standard public path
324 $path = 'Resources/public/'.$path;
325 }
326 }
327
328 //Resolve bundle prefix
329 try {
330 $prefix = $this->locator->locate($bundle);
331 //Catch bundle does not exist or is not enabled exception
332 } catch(\InvalidArgumentException $e) {
333 //Fix lowercase first bundle character
334 if ($bundle[1] > 'Z' || $bundle[1] < 'A') {
335 $bundle[1] = strtoupper($bundle[1]);
336 }
337
338 //Detect double bundle suffix
339 if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') {
340 //Strip extra bundle
341 $bundle = substr($bundle, 0, -strlen('Bundle'));
342 }
343
344 //Convert snake case in camel case
345 if (strpos($bundle, '_') !== false) {
346 //Fix every first character following a _
347 while(($cur = strpos($bundle, '_')) !== false) {
348 $bundle = substr($bundle, 0, $cur).ucfirst(substr($bundle, $cur + 1));
349 }
350 }
351
352 //Resolve fixed bundle prefix
353 try {
354 $prefix = $this->locator->locate($bundle);
355 //Catch bundle does not exist or is not enabled exception again
356 } catch(\InvalidArgumentException $e) {
357 //Bail out as bundle or path is invalid and we have no way to know what was meant
358 throw new Error(sprintf('Invalid bundle name "%s" in path "%s". Maybe you meant "%s"', substr($file, 1, $pos - 1), $file, $bundle.'/'.$path), $lineno, $source, $e);
359 }
360 }
361
362 //Return solved bundle prefix and path
363 return $prefix.$path;
364 }
365 }