Add a Twig_FactoryRuntimeLoader

This commit is contained in:
Robin Chalas
2016-12-22 16:10:39 +01:00
parent 9b31db1ee6
commit 91c8d59978
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();
}