4 * This file is part of Twig.
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
14 * Default base class for compiled templates.
16 * This class is an implementation detail of how template compilation currently
17 * works, which might change. It should never be used directly. Use $twig->load()
18 * instead, which returns an instance of Twig_TemplateWrapper.
20 * @author Fabien Potencier <fabien@symfony.com>
24 abstract class Twig_Template implements Twig_TemplateInterface
29 protected static $cache = array();
32 protected $parents = array();
34 protected $blocks = array();
35 protected $traits = array();
37 public function __construct(Twig_Environment $env)
43 * @internal this method will be removed in 2.0 and is only used internally to provide an upgrade path from 1.x to 2.0
45 public function __toString()
47 return $this->getTemplateName();
51 * Returns the template name.
53 * @return string The template name
55 abstract public function getTemplateName();
58 * Returns debug information about the template.
60 * @return array Debug information
64 public function getDebugInfo()
70 * Returns the template source code.
72 * @return string The template source code
74 * @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead
76 public function getSource()
78 @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
84 * Returns information about the original template source code.
88 public function getSourceContext()
90 return new Twig_Source('', $this->getTemplateName());
94 * @deprecated since 1.20 (to be removed in 2.0)
96 public function getEnvironment()
98 @trigger_error('The '.__METHOD__.' method is deprecated since version 1.20 and will be removed in 2.0.', E_USER_DEPRECATED);
104 * Returns the parent template.
106 * This method is for internal use only and should never be called
109 * @param array $context
111 * @return Twig_TemplateInterface|false The parent template or false if there is no parent
115 public function getParent(array $context)
117 if (null !== $this->parent) {
118 return $this->parent;
122 $parent = $this->doGetParent($context);
124 if (false === $parent) {
128 if ($parent instanceof self) {
129 return $this->parents[$parent->getTemplateName()] = $parent;
132 if (!isset($this->parents[$parent])) {
133 $this->parents[$parent] = $this->loadTemplate($parent);
135 } catch (Twig_Error_Loader $e) {
136 $e->setSourceContext(null);
142 return $this->parents[$parent];
145 protected function doGetParent(array $context)
150 public function isTraitable()
156 * Displays a parent block.
158 * This method is for internal use only and should never be called
161 * @param string $name The block name to display from the parent
162 * @param array $context The context
163 * @param array $blocks The current set of blocks
167 public function displayParentBlock($name, array $context, array $blocks = array())
169 $name = (string) $name;
171 if (isset($this->traits[$name])) {
172 $this->traits[$name][0]->displayBlock($name, $context, $blocks, false);
173 } elseif (false !== $parent = $this->getParent($context)) {
174 $parent->displayBlock($name, $context, $blocks, false);
176 throw new Twig_Error_Runtime(sprintf('The template has no parent and no traits defining the "%s" block.', $name), -1, $this->getSourceContext());
183 * This method is for internal use only and should never be called
186 * @param string $name The block name to display
187 * @param array $context The context
188 * @param array $blocks The current set of blocks
189 * @param bool $useBlocks Whether to use the current set of blocks
193 public function displayBlock($name, array $context, array $blocks = array(), $useBlocks = true)
195 $name = (string) $name;
197 if ($useBlocks && isset($blocks[$name])) {
198 $template = $blocks[$name][0];
199 $block = $blocks[$name][1];
200 } elseif (isset($this->blocks[$name])) {
201 $template = $this->blocks[$name][0];
202 $block = $this->blocks[$name][1];
208 // avoid RCEs when sandbox is enabled
209 if (null !== $template && !$template instanceof self) {
210 throw new LogicException('A block must be a method on a Twig_Template instance.');
213 if (null !== $template) {
215 $template->$block($context, $blocks);
216 } catch (Twig_Error $e) {
217 if (!$e->getSourceContext()) {
218 $e->setSourceContext($template->getSourceContext());
221 // this is mostly useful for Twig_Error_Loader exceptions
222 // see Twig_Error_Loader
223 if (false === $e->getTemplateLine()) {
224 $e->setTemplateLine(-1);
229 } catch (Exception $e) {
230 throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getSourceContext(), $e);
232 } elseif (false !== $parent = $this->getParent($context)) {
233 $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks), false);
235 @trigger_error(sprintf('Silent display of undefined block "%s" in template "%s" is deprecated since version 1.29 and will throw an exception in 2.0. Use the "block(\'%s\') is defined" expression to test for block existence.', $name, $this->getTemplateName(), $name), E_USER_DEPRECATED);
240 * Renders a parent block.
242 * This method is for internal use only and should never be called
245 * @param string $name The block name to render from the parent
246 * @param array $context The context
247 * @param array $blocks The current set of blocks
249 * @return string The rendered block
253 public function renderParentBlock($name, array $context, array $blocks = array())
256 $this->displayParentBlock($name, $context, $blocks);
258 return ob_get_clean();
264 * This method is for internal use only and should never be called
267 * @param string $name The block name to render
268 * @param array $context The context
269 * @param array $blocks The current set of blocks
270 * @param bool $useBlocks Whether to use the current set of blocks
272 * @return string The rendered block
276 public function renderBlock($name, array $context, array $blocks = array(), $useBlocks = true)
279 $this->displayBlock($name, $context, $blocks, $useBlocks);
281 return ob_get_clean();
285 * Returns whether a block exists or not in the current context of the template.
287 * This method checks blocks defined in the current template
288 * or defined in "used" traits or defined in parent templates.
290 * @param string $name The block name
291 * @param array $context The context
292 * @param array $blocks The current set of blocks
294 * @return bool true if the block exists, false otherwise
298 public function hasBlock($name, array $context = null, array $blocks = array())
300 if (null === $context) {
301 @trigger_error('The '.__METHOD__.' method is internal and should never be called; calling it directly is deprecated since version 1.28 and won\'t be possible anymore in 2.0.', E_USER_DEPRECATED);
303 return isset($this->blocks[(string) $name]);
306 if (isset($blocks[$name])) {
307 return $blocks[$name][0] instanceof self;
310 if (isset($this->blocks[$name])) {
314 if (false !== $parent = $this->getParent($context)) {
315 return $parent->hasBlock($name, $context);
322 * Returns all block names in the current context of the template.
324 * This method checks blocks defined in the current template
325 * or defined in "used" traits or defined in parent templates.
327 * @param array $context The context
328 * @param array $blocks The current set of blocks
330 * @return array An array of block names
334 public function getBlockNames(array $context = null, array $blocks = array())
336 if (null === $context) {
337 @trigger_error('The '.__METHOD__.' method is internal and should never be called; calling it directly is deprecated since version 1.28 and won\'t be possible anymore in 2.0.', E_USER_DEPRECATED);
339 return array_keys($this->blocks);
342 $names = array_merge(array_keys($blocks), array_keys($this->blocks));
344 if (false !== $parent = $this->getParent($context)) {
345 $names = array_merge($names, $parent->getBlockNames($context));
348 return array_unique($names);
351 protected function loadTemplate($template, $templateName = null, $line = null, $index = null)
354 if (is_array($template)) {
355 return $this->env->resolveTemplate($template);
358 if ($template instanceof self) {
362 if ($template instanceof Twig_TemplateWrapper) {
366 return $this->env->loadTemplate($template, $index);
367 } catch (Twig_Error $e) {
368 if (!$e->getSourceContext()) {
369 $e->setSourceContext($templateName ? new Twig_Source('', $templateName) : $this->getSourceContext());
372 if ($e->getTemplateLine()) {
379 $e->setTemplateLine($line);
387 * Returns all blocks.
389 * This method is for internal use only and should never be called
392 * @return array An array of blocks
396 public function getBlocks()
398 return $this->blocks;
401 public function display(array $context, array $blocks = array())
403 $this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks));
406 public function render(array $context)
408 $level = ob_get_level();
411 $this->display($context);
412 } catch (Exception $e) {
413 while (ob_get_level() > $level) {
418 } catch (Throwable $e) {
419 while (ob_get_level() > $level) {
426 return ob_get_clean();
429 protected function displayWithErrorHandling(array $context, array $blocks = array())
432 $this->doDisplay($context, $blocks);
433 } catch (Twig_Error $e) {
434 if (!$e->getSourceContext()) {
435 $e->setSourceContext($this->getSourceContext());
438 // this is mostly useful for Twig_Error_Loader exceptions
439 // see Twig_Error_Loader
440 if (false === $e->getTemplateLine()) {
441 $e->setTemplateLine(-1);
446 } catch (Exception $e) {
447 throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getSourceContext(), $e);
452 * Auto-generated method to display the template with the given context.
454 * @param array $context An array of parameters to pass to the template
455 * @param array $blocks An array of blocks to pass to the template
457 abstract protected function doDisplay(array $context, array $blocks = array());
460 * Returns a variable from the context.
462 * This method is for internal use only and should never be called
465 * This method should not be overridden in a sub-class as this is an
466 * implementation detail that has been introduced to optimize variable
467 * access for versions of PHP before 5.4. This is not a way to override
468 * the way to get a variable value.
470 * @param array $context The context
471 * @param string $item The variable to return from the context
472 * @param bool $ignoreStrictCheck Whether to ignore the strict variable check or not
474 * @return mixed The content of the context variable
476 * @throws Twig_Error_Runtime if the variable does not exist and Twig is running in strict mode
480 final protected function getContext($context, $item, $ignoreStrictCheck = false)
482 if (!array_key_exists($item, $context)) {
483 if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
487 throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist.', $item), -1, $this->getSourceContext());
490 return $context[$item];
494 * Returns the attribute value for a given array/object.
496 * @param mixed $object The object or array from where to get the item
497 * @param mixed $item The item to get from the array or object
498 * @param array $arguments An array of arguments to pass if the item is an object method
499 * @param string $type The type of attribute (@see Twig_Template constants)
500 * @param bool $isDefinedTest Whether this is only a defined check
501 * @param bool $ignoreStrictCheck Whether to ignore the strict attribute check or not
503 * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true
505 * @throws Twig_Error_Runtime if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false
509 protected function getAttribute($object, $item, array $arguments = array(), $type = self::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
512 if (self::METHOD_CALL !== $type) {
513 $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item;
515 if ((is_array($object) && (isset($object[$arrayItem]) || array_key_exists($arrayItem, $object)))
516 || ($object instanceof ArrayAccess && isset($object[$arrayItem]))
518 if ($isDefinedTest) {
522 return $object[$arrayItem];
525 if (self::ARRAY_CALL === $type || !is_object($object)) {
526 if ($isDefinedTest) {
530 if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
534 if ($object instanceof ArrayAccess) {
535 $message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, get_class($object));
536 } elseif (is_object($object)) {
537 $message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, get_class($object));
538 } elseif (is_array($object)) {
539 if (empty($object)) {
540 $message = sprintf('Key "%s" does not exist as the array is empty.', $arrayItem);
542 $message = sprintf('Key "%s" for array with keys "%s" does not exist.', $arrayItem, implode(', ', array_keys($object)));
544 } elseif (self::ARRAY_CALL === $type) {
545 if (null === $object) {
546 $message = sprintf('Impossible to access a key ("%s") on a null variable.', $item);
548 $message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s").', $item, gettype($object), $object);
550 } elseif (null === $object) {
551 $message = sprintf('Impossible to access an attribute ("%s") on a null variable.', $item);
553 $message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").', $item, gettype($object), $object);
556 throw new Twig_Error_Runtime($message, -1, $this->getSourceContext());
560 if (!is_object($object)) {
561 if ($isDefinedTest) {
565 if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
569 if (null === $object) {
570 $message = sprintf('Impossible to invoke a method ("%s") on a null variable.', $item);
571 } elseif (is_array($object)) {
572 $message = sprintf('Impossible to invoke a method ("%s") on an array.', $item);
574 $message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").', $item, gettype($object), $object);
577 throw new Twig_Error_Runtime($message, -1, $this->getSourceContext());
581 if (self::METHOD_CALL !== $type && !$object instanceof self) { // Twig_Template does not have public properties, and we don't want to allow access to internal ones
582 if (isset($object->$item) || array_key_exists((string) $item, $object)) {
583 if ($isDefinedTest) {
587 if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
588 $this->env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item);
591 return $object->$item;
595 $class = get_class($object);
598 if (!isset(self::$cache[$class])) {
599 // get_class_methods returns all methods accessible in the scope, but we only want public ones to be accessible in templates
600 if ($object instanceof self) {
601 $ref = new ReflectionClass($class);
604 foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $refMethod) {
605 // Accessing the environment from templates is forbidden to prevent untrusted changes to the environment
606 if ('getenvironment' !== strtolower($refMethod->name)) {
607 $methods[] = $refMethod->name;
611 $methods = get_class_methods($object);
613 // sort values to have consistent behavior, so that "get" methods win precedence over "is" methods
618 foreach ($methods as $method) {
619 $cache[$method] = $method;
620 $cache[$lcName = strtolower($method)] = $method;
622 if ('g' === $lcName[0] && 0 === strpos($lcName, 'get')) {
623 $name = substr($method, 3);
624 $lcName = substr($lcName, 3);
625 } elseif ('i' === $lcName[0] && 0 === strpos($lcName, 'is')) {
626 $name = substr($method, 2);
627 $lcName = substr($lcName, 2);
632 // skip get() and is() methods (in which case, $name is empty)
634 if (!isset($cache[$name])) {
635 $cache[$name] = $method;
637 if (!isset($cache[$lcName])) {
638 $cache[$lcName] = $method;
642 self::$cache[$class] = $cache;
646 if (isset(self::$cache[$class][$item])) {
647 $method = self::$cache[$class][$item];
648 } elseif (isset(self::$cache[$class][$lcItem = strtolower($item)])) {
649 $method = self::$cache[$class][$lcItem];
650 } elseif (isset(self::$cache[$class]['__call'])) {
654 if ($isDefinedTest) {
658 if ($ignoreStrictCheck || !$this->env->isStrictVariables()) {
662 throw new Twig_Error_Runtime(sprintf('Neither the property "%1$s" nor one of the methods "%1$s()", "get%1$s()"/"is%1$s()" or "__call()" exist and have public access in class "%2$s".', $item, $class), -1, $this->getSourceContext());
665 if ($isDefinedTest) {
669 if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
670 $this->env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method);
673 // Some objects throw exceptions when they have __call, and the method we try
674 // to call is not supported. If ignoreStrictCheck is true, we should return null.
677 $ret = $object->$method();
679 $ret = call_user_func_array(array($object, $method), $arguments);
681 } catch (BadMethodCallException $e) {
682 if ($call && ($ignoreStrictCheck || !$this->env->isStrictVariables())) {
688 // @deprecated in 1.28
689 if ($object instanceof Twig_TemplateInterface) {
690 $self = $object->getTemplateName() === $this->getTemplateName();
691 $message = sprintf('Calling "%s" on template "%s" from template "%s" is deprecated since version 1.28 and won\'t be supported anymore in 2.0.', $item, $object->getTemplateName(), $this->getTemplateName());
692 if ('renderBlock' === $method || 'displayBlock' === $method) {
693 $message .= sprintf(' Use block("%s"%s) instead).', $arguments[0], $self ? '' : ', template');
694 } elseif ('hasBlock' === $method) {
695 $message .= sprintf(' Use "block("%s"%s) is defined" instead).', $arguments[0], $self ? '' : ', template');
696 } elseif ('render' === $method || 'display' === $method) {
697 $message .= sprintf(' Use include("%s") instead).', $object->getTemplateName());
699 @trigger_error($message, E_USER_DEPRECATED);
701 return '' === $ret ? '' : new Twig_Markup($ret, $this->env->getCharset());
708 class_alias('Twig_Template', 'Twig\Template', false);