diff --git a/CHANGELOG b/CHANGELOG index 2acb88dfb..f42fb5250 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -75,7 +75,7 @@ * 1.34.5 (2017-XX-XX) - * n/a + * added circular reference detection when loading templates * 1.34.4 (2017-07-04) diff --git a/lib/Twig/Environment.php b/lib/Twig/Environment.php index a9b4374eb..b13ef8cce 100644 --- a/lib/Twig/Environment.php +++ b/lib/Twig/Environment.php @@ -42,6 +42,7 @@ class Twig_Environment private $runtimeLoaders = array(); private $runtimes = array(); private $optionsHash; + private $loading = array(); /** * Constructor. @@ -382,7 +383,19 @@ class Twig_Environment // to be removed in 3.0 $this->extensionSet->initRuntime($this); - return $this->loadedTemplates[$cls] = new $cls($this); + if (isset($this->loading[$cls])) { + throw new Twig_Error_Runtime(sprintf('Circular reference detected for Twig template "%s", path: %s.', $name, implode(' -> ', array_merge($this->loading, array($name))))); + } + + $this->loading[$cls] = $name; + + try { + $this->loadedTemplates[$cls] = new $cls($this); + } finally { + unset($this->loading[$cls]); + } + + return $this->loadedTemplates[$cls]; } /** diff --git a/test/Twig/Tests/EnvironmentTest.php b/test/Twig/Tests/EnvironmentTest.php index d1af5dc20..ae02bb954 100644 --- a/test/Twig/Tests/EnvironmentTest.php +++ b/test/Twig/Tests/EnvironmentTest.php @@ -352,6 +352,33 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase $twig->loadTemplate($template, 'abc'); } + /** + * @expectedException Twig_Error_Runtime + * @expectedExceptionMessage Circular reference detected for Twig template "base.html.twig", path: base.html.twig -> base.html.twig in "base.html.twig" at line 1 + */ + public function testFailLoadTemplateOnCircularReference() + { + $twig = new Twig_Environment(new Twig_Loader_Array(array( + 'base.html.twig' => '{% extends "base.html.twig" %}', + ))); + + $twig->loadTemplate('base.html.twig'); + } + + /** + * @expectedException Twig_Error_Runtime + * @expectedExceptionMessage Circular reference detected for Twig template "base1.html.twig", path: base1.html.twig -> base2.html.twig -> base1.html.twig in "base1.html.twig" at line 1 + */ + public function testFailLoadTemplateOnComplexCircularReference() + { + $twig = new Twig_Environment(new Twig_Loader_Array(array( + 'base1.html.twig' => '{% extends "base2.html.twig" %}', + 'base2.html.twig' => '{% extends "base1.html.twig" %}', + ))); + + $twig->loadTemplate('base1.html.twig'); + } + protected function getMockLoader($templateName, $templateContent) { $loader = $this->getMockBuilder('Twig_LoaderInterface')->getMock();