diff --git a/composer.json b/composer.json index b1ef8f220..4c64e609b 100644 --- a/composer.json +++ b/composer.json @@ -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" : { diff --git a/lib/Twig/ContainerRuntimeLoader.php b/lib/Twig/ContainerRuntimeLoader.php new file mode 100644 index 000000000..df42e0a14 --- /dev/null +++ b/lib/Twig/ContainerRuntimeLoader.php @@ -0,0 +1,37 @@ + + * @author Robin Chalas + */ +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); + } + } +} diff --git a/test/Twig/Tests/ContainerRuntimeLoaderTest.php b/test/Twig/Tests/ContainerRuntimeLoaderTest.php new file mode 100644 index 000000000..1557a15a8 --- /dev/null +++ b/test/Twig/Tests/ContainerRuntimeLoaderTest.php @@ -0,0 +1,35 @@ +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')); + } +}