merged branch fabpot/twig-engine-exists (PR #8547)

This PR was merged into the 2.2 branch.

Discussion
----------

[Twig] fixed TwigEngine::exists() method when a template contains a syntax error (closes #8546)

| Q             | A
| ------------- | ---
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #8546
| License       | MIT
| Doc PR        | n/a

Commits
-------

ae7fa11 [Twig] fixed TwigEngine::exists() method when a template contains a syntax error (closes #88546)
This commit is contained in:
Fabien Potencier 2013-07-23 16:07:56 +02:00
commit ea01eeb3b0
2 changed files with 68 additions and 2 deletions

View File

@ -0,0 +1,56 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Twig\Tests;
use Symfony\Bridge\Twig\TwigEngine;
class TwigEngineTest extends TestCase
{
public function testExistsWithTemplateInstances()
{
$engine = $this->getTwig();
$this->assertTrue($engine->exists($this->getMockForAbstractClass('Twig_Template', array(), '', false)));
}
public function testExistsWithNonExistentTemplates()
{
$engine = $this->getTwig();
$this->assertFalse($engine->exists('foobar'));
}
public function testExistsWithTemplateWithSyntaxErrors()
{
$engine = $this->getTwig();
$this->assertTrue($engine->exists('error'));
}
public function testExists()
{
$engine = $this->getTwig();
$this->assertTrue($engine->exists('index'));
}
protected function getTwig()
{
$twig = new \Twig_Environment(new \Twig_Loader_Array(array(
'index' => 'foo',
'error' => '{{ foo }',
)));
$parser = $this->getMock('Symfony\Component\Templating\TemplateNameParserInterface');
return new TwigEngine($twig, $parser);
}
}

View File

@ -75,9 +75,19 @@ class TwigEngine implements EngineInterface, StreamingEngineInterface
*/
public function exists($name)
{
if ($name instanceof \Twig_Template) {
return true;
}
$loader = $this->environment->getLoader();
if ($loader instanceof \Twig_ExistsLoaderInterface) {
return $loader->exists($name);
}
try {
$this->load($name);
} catch (\InvalidArgumentException $e) {
$loader->getSource($name);
} catch (\Twig_Error_Loader $e) {
return false;
}