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