PageRenderTime 28ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/twig/twig/lib/Twig/Lexer.php

https://bitbucket.org/laborautonomo/laborautonomo-site
PHP | 408 lines | 310 code | 55 blank | 43 comment | 46 complexity | 20c14ffc9046df1d252e8158f28fd893 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. * (c) 2009 Armin Ronacher
  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. * Lexes a template string.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Twig_Lexer implements Twig_LexerInterface
  17. {
  18. protected $tokens;
  19. protected $code;
  20. protected $cursor;
  21. protected $lineno;
  22. protected $end;
  23. protected $state;
  24. protected $states;
  25. protected $brackets;
  26. protected $env;
  27. protected $filename;
  28. protected $options;
  29. protected $regexes;
  30. protected $position;
  31. protected $positions;
  32. protected $currentVarBlockLine;
  33. const STATE_DATA = 0;
  34. const STATE_BLOCK = 1;
  35. const STATE_VAR = 2;
  36. const STATE_STRING = 3;
  37. const STATE_INTERPOLATION = 4;
  38. const REGEX_NAME = '/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A';
  39. const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?/A';
  40. const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As';
  41. const REGEX_DQ_STRING_DELIM = '/"/A';
  42. const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As';
  43. const PUNCTUATION = '()[]{}?:.,|';
  44. public function __construct(Twig_Environment $env, array $options = array())
  45. {
  46. $this->env = $env;
  47. $this->options = array_merge(array(
  48. 'tag_comment' => array('{#', '#}'),
  49. 'tag_block' => array('{%', '%}'),
  50. 'tag_variable' => array('{{', '}}'),
  51. 'whitespace_trim' => '-',
  52. 'interpolation' => array('#{', '}'),
  53. ), $options);
  54. $this->regexes = array(
  55. 'lex_var' => '/\s*'.preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_variable'][1], '/').'/A',
  56. 'lex_block' => '/\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')\n?/A',
  57. 'lex_raw_data' => '/('.preg_quote($this->options['tag_block'][0].$this->options['whitespace_trim'], '/').'|'.preg_quote($this->options['tag_block'][0], '/').')\s*(?:end%s)\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')/s',
  58. 'operator' => $this->getOperatorRegex(),
  59. 'lex_comment' => '/(?:'.preg_quote($this->options['whitespace_trim'], '/').preg_quote($this->options['tag_comment'][1], '/').'\s*|'.preg_quote($this->options['tag_comment'][1], '/').')\n?/s',
  60. 'lex_block_raw' => '/\s*(raw|verbatim)\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')/As',
  61. 'lex_block_line' => '/\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '/').'/As',
  62. 'lex_tokens_start' => '/('.preg_quote($this->options['tag_variable'][0], '/').'|'.preg_quote($this->options['tag_block'][0], '/').'|'.preg_quote($this->options['tag_comment'][0], '/').')('.preg_quote($this->options['whitespace_trim'], '/').')?/s',
  63. 'interpolation_start' => '/'.preg_quote($this->options['interpolation'][0], '/').'\s*/A',
  64. 'interpolation_end' => '/\s*'.preg_quote($this->options['interpolation'][1], '/').'/A',
  65. );
  66. }
  67. /**
  68. * Tokenizes a source code.
  69. *
  70. * @param string $code The source code
  71. * @param string $filename A unique identifier for the source code
  72. *
  73. * @return Twig_TokenStream A token stream instance
  74. */
  75. public function tokenize($code, $filename = null)
  76. {
  77. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  78. $mbEncoding = mb_internal_encoding();
  79. mb_internal_encoding('ASCII');
  80. }
  81. $this->code = str_replace(array("\r\n", "\r"), "\n", $code);
  82. $this->filename = $filename;
  83. $this->cursor = 0;
  84. $this->lineno = 1;
  85. $this->end = strlen($this->code);
  86. $this->tokens = array();
  87. $this->state = self::STATE_DATA;
  88. $this->states = array();
  89. $this->brackets = array();
  90. $this->position = -1;
  91. // find all token starts in one go
  92. preg_match_all($this->regexes['lex_tokens_start'], $this->code, $matches, PREG_OFFSET_CAPTURE);
  93. $this->positions = $matches;
  94. while ($this->cursor < $this->end) {
  95. // dispatch to the lexing functions depending
  96. // on the current state
  97. switch ($this->state) {
  98. case self::STATE_DATA:
  99. $this->lexData();
  100. break;
  101. case self::STATE_BLOCK:
  102. $this->lexBlock();
  103. break;
  104. case self::STATE_VAR:
  105. $this->lexVar();
  106. break;
  107. case self::STATE_STRING:
  108. $this->lexString();
  109. break;
  110. case self::STATE_INTERPOLATION:
  111. $this->lexInterpolation();
  112. break;
  113. }
  114. }
  115. $this->pushToken(Twig_Token::EOF_TYPE);
  116. if (!empty($this->brackets)) {
  117. list($expect, $lineno) = array_pop($this->brackets);
  118. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  119. }
  120. if (isset($mbEncoding)) {
  121. mb_internal_encoding($mbEncoding);
  122. }
  123. return new Twig_TokenStream($this->tokens, $this->filename);
  124. }
  125. protected function lexData()
  126. {
  127. // if no matches are left we return the rest of the template as simple text token
  128. if ($this->position == count($this->positions[0]) - 1) {
  129. $this->pushToken(Twig_Token::TEXT_TYPE, substr($this->code, $this->cursor));
  130. $this->cursor = $this->end;
  131. return;
  132. }
  133. // Find the first token after the current cursor
  134. $position = $this->positions[0][++$this->position];
  135. while ($position[1] < $this->cursor) {
  136. if ($this->position == count($this->positions[0]) - 1) {
  137. return;
  138. }
  139. $position = $this->positions[0][++$this->position];
  140. }
  141. // push the template text first
  142. $text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor);
  143. if (isset($this->positions[2][$this->position][0])) {
  144. $text = rtrim($text);
  145. }
  146. $this->pushToken(Twig_Token::TEXT_TYPE, $text);
  147. $this->moveCursor($textContent.$position[0]);
  148. switch ($this->positions[1][$this->position][0]) {
  149. case $this->options['tag_comment'][0]:
  150. $this->lexComment();
  151. break;
  152. case $this->options['tag_block'][0]:
  153. // raw data?
  154. if (preg_match($this->regexes['lex_block_raw'], $this->code, $match, null, $this->cursor)) {
  155. $this->moveCursor($match[0]);
  156. $this->lexRawData($match[1]);
  157. // {% line \d+ %}
  158. } elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, null, $this->cursor)) {
  159. $this->moveCursor($match[0]);
  160. $this->lineno = (int) $match[1];
  161. } else {
  162. $this->pushToken(Twig_Token::BLOCK_START_TYPE);
  163. $this->pushState(self::STATE_BLOCK);
  164. $this->currentVarBlockLine = $this->lineno;
  165. }
  166. break;
  167. case $this->options['tag_variable'][0]:
  168. $this->pushToken(Twig_Token::VAR_START_TYPE);
  169. $this->pushState(self::STATE_VAR);
  170. $this->currentVarBlockLine = $this->lineno;
  171. break;
  172. }
  173. }
  174. protected function lexBlock()
  175. {
  176. if (empty($this->brackets) && preg_match($this->regexes['lex_block'], $this->code, $match, null, $this->cursor)) {
  177. $this->pushToken(Twig_Token::BLOCK_END_TYPE);
  178. $this->moveCursor($match[0]);
  179. $this->popState();
  180. } else {
  181. $this->lexExpression();
  182. }
  183. }
  184. protected function lexVar()
  185. {
  186. if (empty($this->brackets) && preg_match($this->regexes['lex_var'], $this->code, $match, null, $this->cursor)) {
  187. $this->pushToken(Twig_Token::VAR_END_TYPE);
  188. $this->moveCursor($match[0]);
  189. $this->popState();
  190. } else {
  191. $this->lexExpression();
  192. }
  193. }
  194. protected function lexExpression()
  195. {
  196. // whitespace
  197. if (preg_match('/\s+/A', $this->code, $match, null, $this->cursor)) {
  198. $this->moveCursor($match[0]);
  199. if ($this->cursor >= $this->end) {
  200. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $this->state === self::STATE_BLOCK ? 'block' : 'variable'), $this->currentVarBlockLine, $this->filename);
  201. }
  202. }
  203. // operators
  204. if (preg_match($this->regexes['operator'], $this->code, $match, null, $this->cursor)) {
  205. $this->pushToken(Twig_Token::OPERATOR_TYPE, $match[0]);
  206. $this->moveCursor($match[0]);
  207. }
  208. // names
  209. elseif (preg_match(self::REGEX_NAME, $this->code, $match, null, $this->cursor)) {
  210. $this->pushToken(Twig_Token::NAME_TYPE, $match[0]);
  211. $this->moveCursor($match[0]);
  212. }
  213. // numbers
  214. elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, null, $this->cursor)) {
  215. $number = (float) $match[0]; // floats
  216. if (ctype_digit($match[0]) && $number <= PHP_INT_MAX) {
  217. $number = (int) $match[0]; // integers lower than the maximum
  218. }
  219. $this->pushToken(Twig_Token::NUMBER_TYPE, $number);
  220. $this->moveCursor($match[0]);
  221. }
  222. // punctuation
  223. elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) {
  224. // opening bracket
  225. if (false !== strpos('([{', $this->code[$this->cursor])) {
  226. $this->brackets[] = array($this->code[$this->cursor], $this->lineno);
  227. }
  228. // closing bracket
  229. elseif (false !== strpos(')]}', $this->code[$this->cursor])) {
  230. if (empty($this->brackets)) {
  231. throw new Twig_Error_Syntax(sprintf('Unexpected "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename);
  232. }
  233. list($expect, $lineno) = array_pop($this->brackets);
  234. if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) {
  235. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  236. }
  237. }
  238. $this->pushToken(Twig_Token::PUNCTUATION_TYPE, $this->code[$this->cursor]);
  239. ++$this->cursor;
  240. }
  241. // strings
  242. elseif (preg_match(self::REGEX_STRING, $this->code, $match, null, $this->cursor)) {
  243. $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes(substr($match[0], 1, -1)));
  244. $this->moveCursor($match[0]);
  245. }
  246. // opening double quoted string
  247. elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) {
  248. $this->brackets[] = array('"', $this->lineno);
  249. $this->pushState(self::STATE_STRING);
  250. $this->moveCursor($match[0]);
  251. }
  252. // unlexable
  253. else {
  254. throw new Twig_Error_Syntax(sprintf('Unexpected character "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename);
  255. }
  256. }
  257. protected function lexRawData($tag)
  258. {
  259. if (!preg_match(str_replace('%s', $tag, $this->regexes['lex_raw_data']), $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
  260. throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "%s" block', $tag), $this->lineno, $this->filename);
  261. }
  262. $text = substr($this->code, $this->cursor, $match[0][1] - $this->cursor);
  263. $this->moveCursor($text.$match[0][0]);
  264. if (false !== strpos($match[1][0], $this->options['whitespace_trim'])) {
  265. $text = rtrim($text);
  266. }
  267. $this->pushToken(Twig_Token::TEXT_TYPE, $text);
  268. }
  269. protected function lexComment()
  270. {
  271. if (!preg_match($this->regexes['lex_comment'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
  272. throw new Twig_Error_Syntax('Unclosed comment', $this->lineno, $this->filename);
  273. }
  274. $this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]);
  275. }
  276. protected function lexString()
  277. {
  278. if (preg_match($this->regexes['interpolation_start'], $this->code, $match, null, $this->cursor)) {
  279. $this->brackets[] = array($this->options['interpolation'][0], $this->lineno);
  280. $this->pushToken(Twig_Token::INTERPOLATION_START_TYPE);
  281. $this->moveCursor($match[0]);
  282. $this->pushState(self::STATE_INTERPOLATION);
  283. } elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, null, $this->cursor) && strlen($match[0]) > 0) {
  284. $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes($match[0]));
  285. $this->moveCursor($match[0]);
  286. } elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) {
  287. list($expect, $lineno) = array_pop($this->brackets);
  288. if ($this->code[$this->cursor] != '"') {
  289. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  290. }
  291. $this->popState();
  292. ++$this->cursor;
  293. }
  294. }
  295. protected function lexInterpolation()
  296. {
  297. $bracket = end($this->brackets);
  298. if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, null, $this->cursor)) {
  299. array_pop($this->brackets);
  300. $this->pushToken(Twig_Token::INTERPOLATION_END_TYPE);
  301. $this->moveCursor($match[0]);
  302. $this->popState();
  303. } else {
  304. $this->lexExpression();
  305. }
  306. }
  307. protected function pushToken($type, $value = '')
  308. {
  309. // do not push empty text tokens
  310. if (Twig_Token::TEXT_TYPE === $type && '' === $value) {
  311. return;
  312. }
  313. $this->tokens[] = new Twig_Token($type, $value, $this->lineno);
  314. }
  315. protected function moveCursor($text)
  316. {
  317. $this->cursor += strlen($text);
  318. $this->lineno += substr_count($text, "\n");
  319. }
  320. protected function getOperatorRegex()
  321. {
  322. $operators = array_merge(
  323. array('='),
  324. array_keys($this->env->getUnaryOperators()),
  325. array_keys($this->env->getBinaryOperators())
  326. );
  327. $operators = array_combine($operators, array_map('strlen', $operators));
  328. arsort($operators);
  329. $regex = array();
  330. foreach ($operators as $operator => $length) {
  331. // an operator that ends with a character must be followed by
  332. // a whitespace or a parenthesis
  333. if (ctype_alpha($operator[$length - 1])) {
  334. $regex[] = preg_quote($operator, '/').'(?=[\s()])';
  335. } else {
  336. $regex[] = preg_quote($operator, '/');
  337. }
  338. }
  339. return '/'.implode('|', $regex).'/A';
  340. }
  341. protected function pushState($state)
  342. {
  343. $this->states[] = $this->state;
  344. $this->state = $state;
  345. }
  346. protected function popState()
  347. {
  348. if (0 === count($this->states)) {
  349. throw new Exception('Cannot pop state without a previous state');
  350. }
  351. $this->state = array_pop($this->states);
  352. }
  353. }