Template.php 14KB

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