diff --git a/src/Stack/LazyHttpKernel.php b/src/Stack/LazyHttpKernel.php index 8820af6..476837a 100644 --- a/src/Stack/LazyHttpKernel.php +++ b/src/Stack/LazyHttpKernel.php @@ -9,7 +9,7 @@ class LazyHttpKernel implements HttpKernelInterface { private $factory; - private $app; + protected $app; public function __construct(callable $factory) { diff --git a/src/Stack/LazyTerminableHttpKernel.php b/src/Stack/LazyTerminableHttpKernel.php new file mode 100644 index 0000000..83f748a --- /dev/null +++ b/src/Stack/LazyTerminableHttpKernel.php @@ -0,0 +1,18 @@ +app instanceof TerminableInterface) { + return $this->app->terminate($request, $response); + } + } +} diff --git a/src/Stack/functions.php b/src/Stack/functions.php index d235158..11bcccf 100644 --- a/src/Stack/functions.php +++ b/src/Stack/functions.php @@ -2,7 +2,7 @@ namespace Stack; -function lazy(callable $factory) +function lazy(callable $factory, $terminable = false) { - return new LazyHttpKernel($factory); + return $terminable ? new LazyTerminableHttpKernel($factory) : new LazyHttpKernel($factory); } diff --git a/tests/unit/Stack/LazyTerminableHttpKernelTest.php b/tests/unit/Stack/LazyTerminableHttpKernelTest.php new file mode 100644 index 0000000..332c95a --- /dev/null +++ b/tests/unit/Stack/LazyTerminableHttpKernelTest.php @@ -0,0 +1,77 @@ +createHelloKernel(); + }, true); + + // if the lazy kernel did not handle a request it should not be instantiated nor terminated + $request = Request::create('/'); + $kernel->terminate($request, Response::create('fake response')); + $this->assertNull($app); + + // if the kernel handled a request and the underlying instance should be instantiated and terminated + $response = $kernel->handle($request); + $this->assertInstanceOf('Stack\CallableTerminableHttpKernel', $app); + $this->assertFalse($app->isTerminated()); + $kernel->terminate($request, $response); + $this->assertTrue($app->isTerminated()); + } + + + public function testShortcutFunction() + { + $kernel = lazy(function () { + return $this->createHelloKernel(); + }, true); + + $this->assertInstanceOf('Stack\LazyTerminableHttpKernel', $kernel); + $this->assertSame('Hello World!', $kernel->handle(Request::create('/'))->getContent()); + } + + private function createHelloKernel() + { + return $this->createTerminableKernel('Hello World!'); + } + + private function createTerminableKernel($body) + { + return new CallableTerminableHttpKernel(function (Request $request) use ($body) { + return new Response($body); + }); + } +} + +class CallableTerminableHttpKernel extends CallableHttpKernel implements TerminableInterface +{ + private $terminated = false; + + public function terminate(Request $request, Response $response) + { + $this->terminated = true; + } + + public function isTerminated() + { + return $this->terminated; + } +} \ No newline at end of file