feature #2311 Add a simple Twig_RuntimeLoaderInterface implementation (chalasr)

This PR was merged into the 1.x branch.

Discussion
----------

Add a simple Twig_RuntimeLoaderInterface implementation

Next to https://github.com/symfony/symfony/pull/21023

This is related to the BC break reported in symfony/symfony#21008 which has been introduced in symfony/symfony#20093 when decoupling extensions from definitions.

What I propose here is to ease the upgrade to symfony 3.2+ by adding a simple `Twig_RuntimeLoaderInterface` implementation here, useful only when using the twig-bridge outside of the symfony fullstack framework (with the Form component for instance).

Upgrading would be as simple as:

```diff
$twig = new Twig_Environment(...);
$rendererEngine = new TwigRendererEngine(array('form_div_layout.html.twig'), $twig);
- $twig->addExtension(new FormExtension(new TwigRenderer($rendererEngine, $csrfTokenManager)));
+ $twig->addExtension(new FormExtension());
+ $twig->addRuntimeLoader(new Twig_RuntimeLoader(array(TwigRenderer::class => new TwigRenderer($rendererEngine, $csrfTokenManager)));
```

Instead of having to write this runtime loader yourself.
Please see symfony/symfony#21008 for details and a concrete example of how this could help.

Commits
-------

91c8d59 Add a Twig_FactoryRuntimeLoader
This commit is contained in:
Fabien Potencier
2016-12-23 09:11:01 +01:00
2 changed files with 72 additions and 0 deletions
+40
View File
@@ -0,0 +1,40 @@
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Lazy loads the runtime implementations for a Twig element.
*
* @author Robin Chalas <robin.chalas@gmail.com>
*/
class Twig_FactoryRuntimeLoader implements Twig_RuntimeLoaderInterface
{
private $map;
/**
* @param array $map An array of format [classname => factory callable]
*/
public function __construct(array $map = array())
{
$this->map = $map;
}
/**
* {@inheritdoc}
*/
public function load($class)
{
if (isset($this->map[$class])) {
$runtimeFactory = $this->map[$class];
return $runtimeFactory();
}
}
}
@@ -0,0 +1,32 @@
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Twig_Tests_FactoryRuntimeLoaderTest extends PHPUnit_Framework_TestCase
{
public function testLoad()
{
$loader = new Twig_FactoryRuntimeLoader(array('stdClass' => 'getRuntime'));
$this->assertInstanceOf('stdClass', $loader->load('stdClass'));
}
public function testLoadReturnsNullForUnmappedRuntime()
{
$loader = new Twig_FactoryRuntimeLoader();
$this->assertNull($loader->load('stdClass'));
}
}
function getRuntime()
{
return new stdClass();
}