]> Raphaƫl G. Git Repositories - packbundle/blob - Twig/PackTokenParser.php
Switch to new system with generic filters
[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 array $filters The default filters array
20 */
21 public function __construct(FileLocator $fileLocator, ContainerInterface $containerInterface, $prefix, $tag, $output, $filters) {
22 $this->fileLocator = $fileLocator;
23 $this->containerInterface = $containerInterface;
24 $this->prefix = $prefix;
25 $this->tag = $tag;
26 $this->output = $output;
27 $this->filters = $filters;
28
29 if ($this->containerInterface->hasParameter('rapsys_pack')) {
30 if ($parameters = $this->containerInterface->getParameter('rapsys_pack')) {
31 if (isset($parameters['timeout'])) {
32 $timeout = $parameters['timeout'];
33 } elseif (isset($parameters['user_agent'])) {
34 $userAgent = $parameters['user_agent'];
35 } elseif (isset($parameters['redirect'])) {
36 $redirect = $parameters['redirect'];
37 }
38 }
39 }
40
41 //Set http default timeout
42 $this->timeout = ini_get('default_socket_timeout');
43 //Set http default user agent
44 $this->userAgent = ini_get('user_agent');
45 //Set http default redirect
46 $this->redirect = 20;
47
48 //Try to load service defaults
49 if ($this->containerInterface->hasParameter('rapsys_pack')) {
50 if ($parameters = $this->containerInterface->getParameter('rapsys_pack')) {
51 if (!empty($parameters['timeout'])) {
52 $this->timeout = $parameters['timeout'];
53 }
54 if (!empty($parameters['user_agent'])) {
55 $this->userAgent = $parameters['user_agent'];
56 }
57 if (!empty($parameters['redirect'])) {
58 $this->redirect = $parameters['redirect'];
59 }
60 }
61 }
62 }
63
64 public function getTag() {
65 return $this->tag;
66 }
67
68 public function parse(\Twig_Token $token) {
69 $parser = $this->parser;
70 $stream = $this->parser->getStream();
71
72 $inputs = array();
73 $name = 'asset_url';
74 $output = $this->output;
75 $filters = $this->filters;
76
77 $content = '';
78
79 while (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
80 if ($stream->test(\Twig_Token::STRING_TYPE)) {
81 // '@jquery', 'js/src/core/*', 'js/src/extra.js'
82 $inputs[] = $stream->next()->getValue();
83 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'filter')) {
84 // filter='yui_js'
85 $stream->next();
86 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
87 $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $stream->expect(\Twig_Token::STRING_TYPE)->getValue()))));
88 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'output')) {
89 // output='js/packed/*.js' OR output='js/core.js'
90 $stream->next();
91 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
92 $output = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
93 } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'name')) {
94 // name='core_js'
95 $stream->next();
96 $stream->expect(\Twig_Token::OPERATOR_TYPE, '=');
97 $name = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
98 } else {
99 $token = $stream->getCurrent();
100 throw new \Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', \Twig_Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $stream->getSourceContext());
101 }
102 }
103
104 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
105
106 $body = $this->parser->subparse(array($this, 'testEndTag'), true);
107
108 $stream->expect(\Twig_Token::BLOCK_END_TYPE);
109
110 //Replace star with sha1
111 if (($pos = strpos($output, '*')) !== false) {
112 #XXX: assetic code: substr(sha1(serialize($inputs).serialize($filters).serialize($options)), 0, 7)
113 $output = substr($output, 0, $pos).sha1(serialize($inputs).serialize($filters)).substr($output, $pos + 1);
114 }
115
116 //Deal with inputs
117 for($k = 0; $k < count($inputs); $k++) {
118 //Deal with generic url
119 if (strpos($inputs[$k], '//') === 0) {
120 //Default scheme
121 $scheme = 'https://';
122 //Try to load service scheme
123 if ($this->containerInterface->hasParameter('rapsys_pack')) {
124 if ($parameters = $this->containerInterface->getParameter('rapsys_pack')) {
125 if (isset($parameters['scheme'])) {
126 $scheme = $parameters['scheme'];
127 }
128 }
129 }
130 //Fix url
131 $inputs[$k] = $scheme.substr($inputs[$k], 2);
132 //Deal with non url path
133 } elseif (strpos($inputs[$k], '://') === false) {
134 //Check if we have a bundle path
135 if ($inputs[$k][0] == '@') {
136 //Check that we don't have only a path
137 if (($pos = strpos($inputs[$k], '/')) === false) {
138 #TODO: @jquery support (if we really want it)
139 #header('Content-Type: text/plain');
140 #var_dump($inputs);
141 #if ($inputs[0] == '@jquery') {
142 # exit;
143 #}
144 throw new \Twig_Error_Syntax(sprintf('Invalid input path "%s"', $inputs[$k]), $token->getLine(), $stream->getSourceContext());
145 }
146 //Resolve bundle prefix
147 $inputs[$k] = $this->fileLocator->locate(substr($inputs[$k], 0, $pos)).substr($inputs[$k], $pos + 1);
148 }
149 //Deal with globs
150 if (strpos($inputs[$k], '*') !== false || (($a = strpos($inputs[$k], '{')) !== false && ($b = strpos($inputs[$k], ',', $a)) !== false && strpos($inputs[$k], '}', $b) !== false)) {
151 //Get replacement
152 $replacement = glob($inputs[$k], GLOB_NOSORT|GLOB_BRACE);
153 //Check that these are working files
154 foreach($replacement as $input) {
155 if (!is_file($input)) {
156 throw new \Twig_Error_Syntax(sprintf('Input path "%s" from "%s" is not a file', $input, $inputs[$k]), $token->getLine(), $stream->getSourceContext());
157 }
158 }
159 //Replace with glob path
160 array_splice($inputs, $k, 1, $replacement);
161 //Fix current key
162 $k += count($replacement) - 1;
163 //Check that it's a file
164 } elseif (!is_file($inputs[$k])) {
165 throw new \Twig_Error_Syntax(sprintf('Input path "%s" is not a file', $inputs[$k]), $token->getLine(), $stream->getSourceContext());
166 }
167 }
168 }
169
170 //Init context
171 $ctx = stream_context_create(
172 array(
173 'http' => array(
174 'timeout' => $this->timeout,
175 'user_agent' => $this->userAgent,
176 'redirect' => $this->redirect,
177 )
178 )
179 );
180
181 //Check inputs
182 if (!empty($inputs)) {
183 //Retrieve files content
184 foreach($inputs as $input) {
185 //Try to retrieve content
186 if (($data = file_get_contents($input, false, $ctx)) === false) {
187 throw new \Twig_Error_Syntax(sprintf('Unable to retrieve input path "%s"', $input), $token->getLine(), $stream->getSourceContext());
188 }
189 //Append content
190 $content .= $data;
191 }
192 } else {
193 #TODO: trigger error about empty inputs ?
194 }
195
196 //Check filters
197 if (!empty($filters)) {
198 //Apply all filters
199 foreach($filters as $filter) {
200 //Prefix with filter
201 $filter = __NAMESPACE__.'\\Filter\\'.$filter;
202 //Init tool object
203 $tool = new $filter($this->containerInterface, $stream->getSourceContext(), $token->getLine());
204 //Process content
205 $content = $tool->process($content);
206 //Remove object
207 unset($tool);
208 }
209 } else {
210 #TODO: trigger error about empty filters ?
211 }
212
213 //Create output dir on demand
214 if (!is_dir($parent = $dir = dirname($this->prefix.$output))) {
215 //XXX: set as 0777, symfony umask (0022) will reduce rights (0755)
216 mkdir($dir, 0777, true);
217 }
218
219 //Send file content
220 //XXX: atomic rotation is required to avoid partial content in reverse cache
221 if (file_put_contents($this->prefix.$output.'.new', $content) === false) {
222 throw new \Twig_Error_Syntax(sprintf('Unable to write to: %s', $prefix.$output.'.new'), $token->getLine(), $stream->getSourceContext());
223 }
224
225 //Remove old file
226 if (is_file($this->prefix.$output) && unlink($this->prefix.$output) === false) {
227 throw new \Twig_Error_Syntax(sprintf('Unable to unlink: %s', $prefix.$output), $token->getLine(), $stream->getSourceContext());
228 }
229
230 //Rename it
231 if (rename($this->prefix.$output.'.new', $this->prefix.$output) === false) {
232 throw new \Twig_Error_Syntax(sprintf('Unable to rename: %s to %s', $prefix.$output.'.new', $prefix.$output), $token->getLine(), $stream->getSourceContext());
233 }
234
235 //Retrieve asset uri
236 if (($output = $this->containerInterface->get('assets.packages')->getUrl($output, 'rapsys_pack')) === false) {
237 throw new \Twig_Error_Syntax(sprintf('Unable to get url for asset: %s with package %s', $output, 'rapsys_pack'), $token->getLine(), $stream->getSourceContext());
238 }
239
240 //Send pack node
241 return new PackNode(array('value' => $body), array('inputs' => $inputs, 'filters' => $filters, 'name' => $name, 'output' => $output), $token->getLine(), $this->getTag());
242 }
243
244 public function testEndTag(\Twig_Token $token) {
245 return $token->test(array('end'.$this->getTag()));
246 }
247 }