Template.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 base class for compiled templates.
  13. *
  14. * @package twig
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. abstract class Twig_Template implements Twig_TemplateInterface
  18. {
  19. static protected $cache = array();
  20. protected $parents;
  21. protected $env;
  22. protected $blocks;
  23. protected $traits;
  24. /**
  25. * Constructor.
  26. *
  27. * @param Twig_Environment $env A Twig_Environment instance
  28. */
  29. public function __construct(Twig_Environment $env)
  30. {
  31. $this->env = $env;
  32. $this->blocks = array();
  33. $this->traits = array();
  34. }
  35. /**
  36. * Returns the template name.
  37. *
  38. * @return string The template name
  39. */
  40. abstract public function getTemplateName();
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function getEnvironment()
  45. {
  46. return $this->env;
  47. }
  48. /**
  49. * Returns the parent template.
  50. *
  51. * This method is for internal use only and should never be called
  52. * directly.
  53. *
  54. * @return Twig_TemplateInterface|false The parent template or false if there is no parent
  55. */
  56. public function getParent(array $context)
  57. {
  58. $parent = $this->doGetParent($context);
  59. if (false === $parent) {
  60. return false;
  61. } elseif ($parent instanceof Twig_Template) {
  62. $name = $parent->getTemplateName();
  63. $this->parents[$name] = $parent;
  64. $parent = $name;
  65. } elseif (!isset($this->parents[$parent])) {
  66. $this->parents[$parent] = $this->env->loadTemplate($parent);
  67. }
  68. return $this->parents[$parent];
  69. }
  70. protected function doGetParent(array $context)
  71. {
  72. return false;
  73. }
  74. public function isTraitable()
  75. {
  76. return true;
  77. }
  78. /**
  79. * Displays a parent block.
  80. *
  81. * This method is for internal use only and should never be called
  82. * directly.
  83. *
  84. * @param string $name The block name to display from the parent
  85. * @param array $context The context
  86. * @param array $blocks The current set of blocks
  87. */
  88. public function displayParentBlock($name, array $context, array $blocks = array())
  89. {
  90. if (isset($this->traits[$name])) {
  91. $this->traits[$name][0]->displayBlock($name, $context, $blocks);
  92. } elseif (false !== $parent = $this->getParent($context)) {
  93. $parent->displayBlock($name, $context, $blocks);
  94. } else {
  95. throw new Twig_Error_Runtime(sprintf('The template has no parent and no traits defining the "%s" block', $name), -1, $this->getTemplateName());
  96. }
  97. }
  98. /**
  99. * Displays a block.
  100. *
  101. * This method is for internal use only and should never be called
  102. * directly.
  103. *
  104. * @param string $name The block name to display
  105. * @param array $context The context
  106. * @param array $blocks The current set of blocks
  107. */
  108. public function displayBlock($name, array $context, array $blocks = array())
  109. {
  110. if (isset($blocks[$name])) {
  111. $b = $blocks;
  112. unset($b[$name]);
  113. call_user_func($blocks[$name], $context, $b);
  114. } elseif (isset($this->blocks[$name])) {
  115. call_user_func($this->blocks[$name], $context, $blocks);
  116. } elseif (false !== $parent = $this->getParent($context)) {
  117. $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks));
  118. }
  119. }
  120. /**
  121. * Renders a parent block.
  122. *
  123. * This method is for internal use only and should never be called
  124. * directly.
  125. *
  126. * @param string $name The block name to render from the parent
  127. * @param array $context The context
  128. * @param array $blocks The current set of blocks
  129. *
  130. * @return string The rendered block
  131. */
  132. public function renderParentBlock($name, array $context, array $blocks = array())
  133. {
  134. ob_start();
  135. $this->displayParentBlock($name, $context, $blocks);
  136. return ob_get_clean();
  137. }
  138. /**
  139. * Renders a block.
  140. *
  141. * This method is for internal use only and should never be called
  142. * directly.
  143. *
  144. * @param string $name The block name to render
  145. * @param array $context The context
  146. * @param array $blocks The current set of blocks
  147. *
  148. * @return string The rendered block
  149. */
  150. public function renderBlock($name, array $context, array $blocks = array())
  151. {
  152. ob_start();
  153. $this->displayBlock($name, $context, $blocks);
  154. return ob_get_clean();
  155. }
  156. /**
  157. * Returns whether a block exists or not.
  158. *
  159. * This method is for internal use only and should never be called
  160. * directly.
  161. *
  162. * This method does only return blocks defined in the current template
  163. * or defined in "used" traits.
  164. *
  165. * It does not return blocks from parent templates as the parent
  166. * template name can be dynamic, which is only known based on the
  167. * current context.
  168. *
  169. * @param string $name The block name
  170. *
  171. * @return Boolean true if the block exists, false otherwise
  172. */
  173. public function hasBlock($name)
  174. {
  175. return isset($this->blocks[$name]);
  176. }
  177. /**
  178. * Returns all block names.
  179. *
  180. * This method is for internal use only and should never be called
  181. * directly.
  182. *
  183. * @return array An array of block names
  184. *
  185. * @see hasBlock
  186. */
  187. public function getBlockNames()
  188. {
  189. return array_keys($this->blocks);
  190. }
  191. /**
  192. * Returns all blocks.
  193. *
  194. * This method is for internal use only and should never be called
  195. * directly.
  196. *
  197. * @return array An array of blocks
  198. *
  199. * @see hasBlock
  200. */
  201. public function getBlocks()
  202. {
  203. return $this->blocks;
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. public function display(array $context, array $blocks = array())
  209. {
  210. $this->displayWithErrorHandling($this->mergeContextWithGlobals($context), $blocks);
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function render(array $context)
  216. {
  217. $level = ob_get_level();
  218. ob_start();
  219. try {
  220. $this->display($context);
  221. } catch (Exception $e) {
  222. while (ob_get_level() > $level) {
  223. ob_end_clean();
  224. }
  225. throw $e;
  226. }
  227. return ob_get_clean();
  228. }
  229. protected function mergeContextWithGlobals(array $context)
  230. {
  231. // we don't use array_merge as the context being generally
  232. // bigger than globals, this code is faster.
  233. foreach ($this->env->getGlobals() as $key => $value) {
  234. if (!array_key_exists($key, $context)) {
  235. $context[$key] = $value;
  236. }
  237. }
  238. return $context;
  239. }
  240. protected function displayWithErrorHandling(array $context, array $blocks = array())
  241. {
  242. try {
  243. $this->doDisplay($context, $blocks);
  244. } catch (Twig_Error $e) {
  245. throw $e;
  246. } catch (Exception $e) {
  247. throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, null, $e);
  248. }
  249. }
  250. /**
  251. * Auto-generated method to display the template with the given context.
  252. *
  253. * @param array $context An array of parameters to pass to the template
  254. * @param array $blocks An array of blocks to pass to the template
  255. */
  256. abstract protected function doDisplay(array $context, array $blocks = array());
  257. /**
  258. * Returns a variable from the context.
  259. *
  260. * @param array $context The context
  261. * @param string $item The variable to return from the context
  262. * @param Boolean $ignoreStrictCheck Whether to ignore the strict variable check or not
  263. *
  264. * @return The content of the context variable
  265. *
  266. * @throws Twig_Error_Runtime if the variable does not exist and Twig is running in strict mode
  267. */
  268. protected function getContext($context, $item, $ignoreStrictCheck = false)
  269. {
  270. if (!array_key_exists($item, $context)) {
  271. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  272. return null;
  273. }
  274. throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist', $item));
  275. }
  276. return $context[$item];
  277. }
  278. /**
  279. * Returns the attribute value for a given array/object.
  280. *
  281. * @param mixed $object The object or array from where to get the item
  282. * @param mixed $item The item to get from the array or object
  283. * @param array $arguments An array of arguments to pass if the item is an object method
  284. * @param string $type The type of attribute (@see Twig_TemplateInterface)
  285. * @param Boolean $isDefinedTest Whether this is only a defined check
  286. * @param Boolean $ignoreStrictCheck Whether to ignore the strict attribute check or not
  287. *
  288. * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true
  289. *
  290. * @throws Twig_Error_Runtime if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false
  291. */
  292. protected function getAttribute($object, $item, array $arguments = array(), $type = Twig_TemplateInterface::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
  293. {
  294. $item = (string) $item;
  295. // array
  296. if (Twig_TemplateInterface::METHOD_CALL !== $type) {
  297. if ((is_array($object) && array_key_exists($item, $object))
  298. || ($object instanceof ArrayAccess && isset($object[$item]))
  299. ) {
  300. if ($isDefinedTest) {
  301. return true;
  302. }
  303. return $object[$item];
  304. }
  305. if (Twig_TemplateInterface::ARRAY_CALL === $type) {
  306. if ($isDefinedTest) {
  307. return false;
  308. }
  309. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  310. return null;
  311. }
  312. if (is_object($object)) {
  313. throw new Twig_Error_Runtime(sprintf('Key "%s" in object (with ArrayAccess) of type "%s" does not exist', $item, get_class($object)));
  314. // array
  315. } else {
  316. throw new Twig_Error_Runtime(sprintf('Key "%s" for array with keys "%s" does not exist', $item, implode(', ', array_keys($object))));
  317. }
  318. }
  319. }
  320. if (!is_object($object)) {
  321. if ($isDefinedTest) {
  322. return false;
  323. }
  324. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  325. return null;
  326. }
  327. throw new Twig_Error_Runtime(sprintf('Item "%s" for "%s" does not exist', $item, is_array($object) ? 'Array' : $object));
  328. }
  329. $class = get_class($object);
  330. // object property
  331. if (Twig_TemplateInterface::METHOD_CALL !== $type) {
  332. /* apparently, this is not needed as this is already covered by the array_key_exists() call below
  333. if (!isset(self::$cache[$class]['properties'])) {
  334. foreach (get_object_vars($object) as $k => $v) {
  335. self::$cache[$class]['properties'][$k] = true;
  336. }
  337. }
  338. */
  339. if (isset($object->$item) || array_key_exists($item, $object)) {
  340. if ($isDefinedTest) {
  341. return true;
  342. }
  343. if ($this->env->hasExtension('sandbox')) {
  344. $this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item);
  345. }
  346. return $object->$item;
  347. }
  348. }
  349. // object method
  350. if (!isset(self::$cache[$class]['methods'])) {
  351. self::$cache[$class]['methods'] = array_change_key_case(array_flip(get_class_methods($object)));
  352. }
  353. $lcItem = strtolower($item);
  354. if (isset(self::$cache[$class]['methods'][$lcItem])) {
  355. $method = $item;
  356. } elseif (isset(self::$cache[$class]['methods']['get'.$lcItem])) {
  357. $method = 'get'.$item;
  358. } elseif (isset(self::$cache[$class]['methods']['is'.$lcItem])) {
  359. $method = 'is'.$item;
  360. } elseif (isset(self::$cache[$class]['methods']['__call'])) {
  361. $method = $item;
  362. } else {
  363. if ($isDefinedTest) {
  364. return false;
  365. }
  366. if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
  367. return null;
  368. }
  369. throw new Twig_Error_Runtime(sprintf('Method "%s" for object "%s" does not exist', $item, get_class($object)));
  370. }
  371. if ($isDefinedTest) {
  372. return true;
  373. }
  374. if ($this->env->hasExtension('sandbox')) {
  375. $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method);
  376. }
  377. $ret = call_user_func_array(array($object, $method), $arguments);
  378. // hack to be removed when macro calls are refactored
  379. if ($object instanceof Twig_TemplateInterface) {
  380. return new Twig_Markup($ret, $this->env->getCharset());
  381. }
  382. return $ret;
  383. }
  384. /**
  385. * This method is only useful when testing Twig. Do not use it.
  386. */
  387. static public function clearCache()
  388. {
  389. self::$cache = array();
  390. }
  391. }