Add ContainerRuntimeLoader

This commit is contained in:
Robin Chalas
2017-02-17 18:56:08 +01:00
parent d6715ac8c3
commit 964a51bc02
3 changed files with 74 additions and 1 deletions
+2 -1
View File
@@ -31,7 +31,8 @@
},
"require-dev": {
"symfony/phpunit-bridge": "~3.2",
"symfony/debug": "~2.7"
"symfony/debug": "~2.7",
"psr/container": "^1.0"
},
"autoload": {
"psr-0" : {
+37
View File
@@ -0,0 +1,37 @@
<?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.
*/
use Psr\Container\ContainerInterface;
/**
* Lazily loads Twig runtime implementations from a PSR-11 container.
*
* The runtime services must use their class name as identifier in the container.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Robin Chalas <robin.chalas@gmail.com>
*/
class Twig_ContainerRuntimeLoader implements Twig_RuntimeLoaderInterface
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function load($class)
{
if ($this->container->has($class)) {
return $this->container->get($class);
}
}
}
@@ -0,0 +1,35 @@
<?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.
*/
use Psr\Container\ContainerInterface;
class Twig_Tests_ContainerRuntimeLoaderTest extends PHPUnit_Framework_TestCase
{
public function testLoad()
{
$container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$container->expects($this->once())->method('has')->with('stdClass')->willReturn(true);
$container->expects($this->once())->method('get')->with('stdClass')->willReturn(new \Stdclass());
$loader = new Twig_ContainerRuntimeLoader($container);
$this->assertInstanceOf('stdClass', $loader->load('stdClass'));
}
public function testLoadUnknownRuntimeReturnsNull()
{
$container = $this->getMockBuilder(ContainerInterface::class)->getMock();
$container->expects($this->once())->method('has')->with('Foo');
$container->expects($this->never())->method('get');
$this->assertNull((new Twig_ContainerRuntimeLoader($container))->load('Foo'));
}
}