From c448c28c9940388e1add3bc2e2a80a0e63b40526 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 12 Mar 2018 17:23:59 -0500 Subject: [PATCH] Allow ResponseInterface service to return a factory instead of instance --- src/ProblemDetailsResponseFactoryFactory.php | 17 ++++++++++++++--- ...oblemDetailsResponseFactoryFactoryTest.php | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/ProblemDetailsResponseFactoryFactory.php b/src/ProblemDetailsResponseFactoryFactory.php index bed3df6..773bd39 100644 --- a/src/ProblemDetailsResponseFactoryFactory.php +++ b/src/ProblemDetailsResponseFactoryFactory.php @@ -20,9 +20,7 @@ public function __invoke(ContainerInterface $container) : ProblemDetailsResponse $problemDetailsConfig = $config['problem-details'] ?? []; $jsonFlags = $problemDetailsConfig['json_flags'] ?? null; - $responsePrototype = $container->has(ResponseInterface::class) - ? $container->get(ResponseInterface::class) - : null; + $responsePrototype = $this->getResponsePrototype($container); $streamFactory = $container->has('Zend\ProblemDetails\StreamFactory') ? $container->get('Zend\ProblemDetails\StreamFactory') @@ -36,4 +34,17 @@ public function __invoke(ContainerInterface $container) : ProblemDetailsResponse $includeThrowableDetail ); } + + /** + * @return null|ResponseInterface + */ + private function getResponsePrototype(ContainerInterface $container) + { + if (! $container->has(ResponseInterface::class)) { + return null; + } + + $response = $container->get(ResponseInterface::class); + return is_callable($response) ? $response() : $response; + } } diff --git a/test/ProblemDetailsResponseFactoryFactoryTest.php b/test/ProblemDetailsResponseFactoryFactoryTest.php index 8d92724..57f1389 100644 --- a/test/ProblemDetailsResponseFactoryFactoryTest.php +++ b/test/ProblemDetailsResponseFactoryFactoryTest.php @@ -90,6 +90,25 @@ public function testUsesResponseServiceFromContainerWhenPresent() : void $this->assertAttributeSame($response, 'response', $factory); } + public function testUsesResponseServiceAsFactoryFromContainerWhenPresent() : void + { + $response = $this->prophesize(ResponseInterface::class)->reveal(); + $responseFactory = function () use ($response) { + return $response; + }; + + $this->container->has('config')->willReturn(false); + $this->container->has(ResponseInterface::class)->willReturn(true); + $this->container->get(ResponseInterface::class)->willReturn($responseFactory); + $this->container->has('Zend\ProblemDetails\StreamFactory')->willReturn(false); + + $factoryFactory = new ProblemDetailsResponseFactoryFactory(); + $factory = $factoryFactory($this->container->reveal()); + + $this->assertInstanceOf(ProblemDetailsResponseFactory::class, $factory); + $this->assertAttributeSame($response, 'response', $factory); + } + public function testUsesStreamFactoryServiceFromContainerWhenPresent() : void { // @codingStandardsIgnoreStart