1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys PackBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\PackBundle\Parser
;
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
;
20 use Twig\Node\Expression\AssignNameExpression
;
22 use Twig\Node\SetNode
;
23 use Twig\Node\TextNode
;
26 use Twig\TokenParser\AbstractTokenParser
;
28 use Rapsys\PackBundle\RapsysPackBundle
;
30 class TokenParser
extends AbstractTokenParser
{
32 * The stream context instance
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
46 public function __construct(protected FileLocator
$locator, protected PackageInterface
$package, protected string $token, protected string $tag, protected string $output, protected array $filters) {
48 $this->ctx
= stream_context_create(
51 #'header' => ['Referer: https://www.openstreetmap.org/'],
52 'max_redirects' => $_ENV['RAPSYSPACK_REDIRECT'] ?? 20,
53 'timeout' => $_ENV['RAPSYSPACK_TIMEOUT'] ?? (($timeout = ini_get('default_socket_timeout')) !== false && $timeout !== "" ? (float)$timeout : 60),
54 'user_agent' => $_ENV['RAPSYSPACK_AGENT'] ?? (($agent = ini_get('user_agent')) !== false && $agent !== "" ? (string)$agent : RapsysPackBundle
::getAlias().'/'.RapsysPackBundle
::getVersion())
63 * @return string This tag name
65 public function getTag(): string {
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 ?
76 * @param Token $token The \Twig\Token instance
77 * @return Node The PackNode
79 public function parse(Token
$token): Node
{
81 $parser = $this->parser
;
84 $stream = $this->parser
->getStream();
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();
99 } elseif ($stream->test(Token
::NAME_TYPE
, 'filters')) {
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()))));
105 } elseif ($stream->test(Token
::NAME_TYPE
, 'output')) {
106 //output='js/packed/*.js' OR output='js/core.js'
108 $stream->expect(Token
::OPERATOR_TYPE
, '=');
109 $this->output
= $stream->expect(Token
::STRING_TYPE
)->getValue();
111 } elseif ($stream->test(Token
::NAME_TYPE
, 'token')) {
114 $stream->expect(Token
::OPERATOR_TYPE
, '=');
115 $this->token
= $stream->expect(Token
::STRING_TYPE
)->getValue();
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());
124 $stream->expect(Token
::BLOCK_END_TYPE
);
127 $body = $this->parser
->subparse([$this, 'testEndTag'], true);
130 $stream->expect(Token
::BLOCK_END_TYPE
);
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);
139 for($k = 0; $k < count($inputs); $k++
) {
140 //Deal with generic url
141 if (strpos($inputs[$k], '//') === 0) {
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] == '@') {
149 $inputs[$k] = $this->getLocated($inputs[$k], $token->getLine(), $stream->getSourceContext());
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 //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());
163 //Replace with glob path
164 array_splice($inputs, $k, 1, $replacement);
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());
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());
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());
190 //Send an empty node without inputs
195 if (!empty($this->filters
)) {
197 foreach($this->filters
as $filter) {
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'];
206 $reflection = new \
ReflectionClass($filter['class']);
208 $tool = $reflection->newInstanceArgs($args);
210 $content = $tool->process($content);
212 unset($tool, $reflection);
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());
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());
226 //Check if we have a bundle path
227 if ($this->output
[0] == '@') {
229 $this->output
= $this->getLocated($this->output
, $token->getLine(), $stream->getSourceContext());
233 $filesystem = new Filesystem();
235 //Create output dir if not present
236 if (!is_dir($dir = dirname($this->output
))) {
239 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
240 $filesystem->mkdir($dir, 0775);
241 } catch (IOExceptionInterface
$e) {
243 throw new Error(sprintf('Output directory "%s" do not exists and unable to create it', $dir), $token->getLine(), $stream->getSourceContext(), $e);
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) {
255 throw new Error(sprintf('Unable to write to: %s', $this->output
), $token->getLine(), $stream->getSourceContext(), $e);
258 //Set name in context key
259 $ref = new AssignNameExpression($this->token
, $token->getLine());
261 //Set output in context value
262 $value = new TextNode($outputUrl, $token->getLine());
264 //Send body with context set
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
276 * @param Token $token The \Twig\Token instance
277 * @return bool The token end test result
279 public function testEndTag(Token
$token): bool {
280 return $token->test(['end'.$this->getTag()]);
284 * Get path from bundled file
286 * @see https://symfony.com/doc/current/bundles.html#overridding-the-bundle-directory-structure
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
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');
300 return $this->config['jquery'];
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);
309 $bundle = substr($file, 0, $pos);
312 $path = substr($file, $pos +
1);
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
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;
328 //Resolve bundle prefix
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]);
338 //Detect double bundle suffix
339 if (strlen($bundle) > strlen('_bundleBundle') && substr($bundle, -strlen('_bundleBundle')) == '_bundleBundle') {
341 $bundle = substr($bundle, 0, -strlen('Bundle'));
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));
352 //Resolve fixed bundle prefix
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);
362 //Return solved bundle prefix and path
363 return $prefix.$path;