PageRenderTime 84ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/2012/sample-tonic/src/Twig/Parser.php

https://bitbucket.org/alessandro-aglietti/itis-leonardo-da-vinci
PHP | 395 lines | 278 code | 69 blank | 48 comment | 34 complexity | 3474afff00a350f247b3f45c48b16a62 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. * Default parser implementation.
  13. *
  14. * @package twig
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Twig_Parser implements Twig_ParserInterface
  18. {
  19. protected $stack = array();
  20. protected $stream;
  21. protected $parent;
  22. protected $handlers;
  23. protected $visitors;
  24. protected $expressionParser;
  25. protected $blocks;
  26. protected $blockStack;
  27. protected $macros;
  28. protected $env;
  29. protected $reservedMacroNames;
  30. protected $importedSymbols;
  31. protected $traits;
  32. protected $embeddedTemplates = array();
  33. /**
  34. * Constructor.
  35. *
  36. * @param Twig_Environment $env A Twig_Environment instance
  37. */
  38. public function __construct(Twig_Environment $env)
  39. {
  40. $this->env = $env;
  41. }
  42. public function getEnvironment()
  43. {
  44. return $this->env;
  45. }
  46. public function getVarName()
  47. {
  48. return sprintf('__internal_%s', hash('sha1', uniqid(mt_rand(), true), false));
  49. }
  50. public function getFilename()
  51. {
  52. return $this->stream->getFilename();
  53. }
  54. /**
  55. * Converts a token stream to a node tree.
  56. *
  57. * @param Twig_TokenStream $stream A token stream instance
  58. *
  59. * @return Twig_Node_Module A node tree
  60. */
  61. public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false)
  62. {
  63. // push all variables into the stack to keep the current state of the parser
  64. $vars = get_object_vars($this);
  65. unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser']);
  66. $this->stack[] = $vars;
  67. // tag handlers
  68. if (null === $this->handlers) {
  69. $this->handlers = $this->env->getTokenParsers();
  70. $this->handlers->setParser($this);
  71. }
  72. // node visitors
  73. if (null === $this->visitors) {
  74. $this->visitors = $this->env->getNodeVisitors();
  75. }
  76. if (null === $this->expressionParser) {
  77. $this->expressionParser = new Twig_ExpressionParser($this, $this->env->getUnaryOperators(), $this->env->getBinaryOperators());
  78. }
  79. $this->stream = $stream;
  80. $this->parent = null;
  81. $this->blocks = array();
  82. $this->macros = array();
  83. $this->traits = array();
  84. $this->blockStack = array();
  85. $this->importedSymbols = array(array());
  86. $this->embeddedTemplates = array();
  87. try {
  88. $body = $this->subparse($test, $dropNeedle);
  89. if (null !== $this->parent) {
  90. if (null === $body = $this->filterBodyNodes($body)) {
  91. $body = new Twig_Node();
  92. }
  93. }
  94. } catch (Twig_Error_Syntax $e) {
  95. if (!$e->getTemplateFile()) {
  96. $e->setTemplateFile($this->getFilename());
  97. }
  98. if (!$e->getTemplateLine()) {
  99. $e->setTemplateLine($this->stream->getCurrent()->getLine());
  100. }
  101. throw $e;
  102. }
  103. $node = new Twig_Node_Module(new Twig_Node_Body(array($body)), $this->parent, new Twig_Node($this->blocks), new Twig_Node($this->macros), new Twig_Node($this->traits), $this->embeddedTemplates, $this->getFilename());
  104. $traverser = new Twig_NodeTraverser($this->env, $this->visitors);
  105. $node = $traverser->traverse($node);
  106. // restore previous stack so previous parse() call can resume working
  107. foreach (array_pop($this->stack) as $key => $val) {
  108. $this->$key = $val;
  109. }
  110. return $node;
  111. }
  112. public function subparse($test, $dropNeedle = false)
  113. {
  114. $lineno = $this->getCurrentToken()->getLine();
  115. $rv = array();
  116. while (!$this->stream->isEOF()) {
  117. switch ($this->getCurrentToken()->getType()) {
  118. case Twig_Token::TEXT_TYPE:
  119. $token = $this->stream->next();
  120. $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine());
  121. break;
  122. case Twig_Token::VAR_START_TYPE:
  123. $token = $this->stream->next();
  124. $expr = $this->expressionParser->parseExpression();
  125. $this->stream->expect(Twig_Token::VAR_END_TYPE);
  126. $rv[] = new Twig_Node_Print($expr, $token->getLine());
  127. break;
  128. case Twig_Token::BLOCK_START_TYPE:
  129. $this->stream->next();
  130. $token = $this->getCurrentToken();
  131. if ($token->getType() !== Twig_Token::NAME_TYPE) {
  132. throw new Twig_Error_Syntax('A block must start with a tag name', $token->getLine(), $this->getFilename());
  133. }
  134. if (null !== $test && call_user_func($test, $token)) {
  135. if ($dropNeedle) {
  136. $this->stream->next();
  137. }
  138. if (1 === count($rv)) {
  139. return $rv[0];
  140. }
  141. return new Twig_Node($rv, array(), $lineno);
  142. }
  143. $subparser = $this->handlers->getTokenParser($token->getValue());
  144. if (null === $subparser) {
  145. if (null !== $test) {
  146. $error = sprintf('Unexpected tag name "%s"', $token->getValue());
  147. if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface) {
  148. $error .= sprintf(' (expecting closing tag for the "%s" tag defined near line %s)', $test[0]->getTag(), $lineno);
  149. }
  150. throw new Twig_Error_Syntax($error, $token->getLine(), $this->getFilename());
  151. }
  152. $message = sprintf('Unknown tag name "%s"', $token->getValue());
  153. if ($alternatives = $this->env->computeAlternatives($token->getValue(), array_keys($this->env->getTags()))) {
  154. $message = sprintf('%s. Did you mean "%s"', $message, implode('", "', $alternatives));
  155. }
  156. throw new Twig_Error_Syntax($message, $token->getLine(), $this->getFilename());
  157. }
  158. $this->stream->next();
  159. $node = $subparser->parse($token);
  160. if (null !== $node) {
  161. $rv[] = $node;
  162. }
  163. break;
  164. default:
  165. throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', 0, $this->getFilename());
  166. }
  167. }
  168. if (1 === count($rv)) {
  169. return $rv[0];
  170. }
  171. return new Twig_Node($rv, array(), $lineno);
  172. }
  173. public function addHandler($name, $class)
  174. {
  175. $this->handlers[$name] = $class;
  176. }
  177. public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
  178. {
  179. $this->visitors[] = $visitor;
  180. }
  181. public function getBlockStack()
  182. {
  183. return $this->blockStack;
  184. }
  185. public function peekBlockStack()
  186. {
  187. return $this->blockStack[count($this->blockStack) - 1];
  188. }
  189. public function popBlockStack()
  190. {
  191. array_pop($this->blockStack);
  192. }
  193. public function pushBlockStack($name)
  194. {
  195. $this->blockStack[] = $name;
  196. }
  197. public function hasBlock($name)
  198. {
  199. return isset($this->blocks[$name]);
  200. }
  201. public function getBlock($name)
  202. {
  203. return $this->blocks[$name];
  204. }
  205. public function setBlock($name, $value)
  206. {
  207. $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getLine());
  208. }
  209. public function hasMacro($name)
  210. {
  211. return isset($this->macros[$name]);
  212. }
  213. public function setMacro($name, Twig_Node_Macro $node)
  214. {
  215. if (null === $this->reservedMacroNames) {
  216. $this->reservedMacroNames = array();
  217. $r = new ReflectionClass($this->env->getBaseTemplateClass());
  218. foreach ($r->getMethods() as $method) {
  219. $this->reservedMacroNames[] = $method->getName();
  220. }
  221. }
  222. if (in_array($name, $this->reservedMacroNames)) {
  223. throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword', $name), $node->getLine(), $this->getFilename());
  224. }
  225. $this->macros[$name] = $node;
  226. }
  227. public function addTrait($trait)
  228. {
  229. $this->traits[] = $trait;
  230. }
  231. public function hasTraits()
  232. {
  233. return count($this->traits) > 0;
  234. }
  235. public function embedTemplate(Twig_Node_Module $template)
  236. {
  237. $template->setIndex(mt_rand());
  238. $this->embeddedTemplates[] = $template;
  239. }
  240. public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression $node = null)
  241. {
  242. $this->importedSymbols[0][$type][$alias] = array('name' => $name, 'node' => $node);
  243. }
  244. public function getImportedSymbol($type, $alias)
  245. {
  246. foreach ($this->importedSymbols as $functions) {
  247. if (isset($functions[$type][$alias])) {
  248. return $functions[$type][$alias];
  249. }
  250. }
  251. }
  252. public function isMainScope()
  253. {
  254. return 1 === count($this->importedSymbols);
  255. }
  256. public function pushLocalScope()
  257. {
  258. array_unshift($this->importedSymbols, array());
  259. }
  260. public function popLocalScope()
  261. {
  262. array_shift($this->importedSymbols);
  263. }
  264. /**
  265. * Gets the expression parser.
  266. *
  267. * @return Twig_ExpressionParser The expression parser
  268. */
  269. public function getExpressionParser()
  270. {
  271. return $this->expressionParser;
  272. }
  273. public function getParent()
  274. {
  275. return $this->parent;
  276. }
  277. public function setParent($parent)
  278. {
  279. $this->parent = $parent;
  280. }
  281. /**
  282. * Gets the token stream.
  283. *
  284. * @return Twig_TokenStream The token stream
  285. */
  286. public function getStream()
  287. {
  288. return $this->stream;
  289. }
  290. /**
  291. * Gets the current token.
  292. *
  293. * @return Twig_Token The current token
  294. */
  295. public function getCurrentToken()
  296. {
  297. return $this->stream->getCurrent();
  298. }
  299. protected function filterBodyNodes(Twig_NodeInterface $node)
  300. {
  301. // check that the body does not contain non-empty output nodes
  302. if (
  303. ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data')))
  304. ||
  305. (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface)
  306. ) {
  307. if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
  308. throw new Twig_Error_Syntax('A template that extends another one cannot have a body but a byte order mark (BOM) has been detected; it must be removed.', $node->getLine(), $this->getFilename());
  309. }
  310. throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->getFilename());
  311. }
  312. // bypass "set" nodes as they "capture" the output
  313. if ($node instanceof Twig_Node_Set) {
  314. return $node;
  315. }
  316. if ($node instanceof Twig_NodeOutputInterface) {
  317. return;
  318. }
  319. foreach ($node as $k => $n) {
  320. if (null !== $n && null === $n = $this->filterBodyNodes($n)) {
  321. $node->removeNode($k);
  322. }
  323. }
  324. return $node;
  325. }
  326. }