diff --git a/src/pjdietz/WellRESTed/Router.php b/src/pjdietz/WellRESTed/Router.php index 5a38891..68e5de2 100644 --- a/src/pjdietz/WellRESTed/Router.php +++ b/src/pjdietz/WellRESTed/Router.php @@ -58,15 +58,9 @@ class Router implements HandlerInterface if ($response) { // Check if the router has an error handler for this status code. $status = $response->getStatusCode(); - if (array_key_exists($status, $this->errorHandlers)) { - /** @var HandlerInterface $errorHandler */ - $errorHandler = new $this->errorHandlers[$status](); - // Pass the response triggering this along to the error handler. - $errorArgs = array("response" => $response); - if ($args) { - $errorArgs = array_merge($args, $errorArgs); - } - return $errorHandler->getResponse($request, $errorArgs); + $errorResponse = $this->getErrorResponse($status, $request, $args, $response); + if ($errorResponse) { + return $errorResponse; } } return $response; @@ -181,11 +175,31 @@ class Router implements HandlerInterface */ protected function getNoRouteResponse(RequestInterface $request) { + $response = $this->getErrorResponse(404, $request); + if ($response) { + return $response; + } + $response = new Response(404); $response->setBody('No resource at ' . $request->getPath()); return $response; } + private function getErrorResponse($status, $request, $args = null, $response = null) + { + if (isset($this->errorHandlers[$status])) { + /** @var HandlerInterface $errorHandler */ + $errorHandler = new $this->errorHandlers[$status](); + // Pass the response triggering this along to the error handler. + $errorArgs = array("response" => $response); + if ($args) { + $errorArgs = array_merge($args, $errorArgs); + } + return $errorHandler->getResponse($request, $errorArgs); + } + return null; + } + /** * Returning the matching static handler, or null if none match. * @@ -194,7 +208,7 @@ class Router implements HandlerInterface */ private function getStaticHandler($path) { - if (array_key_exists($path, $this->staticRoutes)) { + if (isset($this->staticRoutes[$path])) { // Instantiate and return the handler identified by the path. return new $this->staticRoutes[$path](); } diff --git a/test/RouterTest.php b/test/RouterTest.php index d978089..011baf4 100644 --- a/test/RouterTest.php +++ b/test/RouterTest.php @@ -249,6 +249,26 @@ class RouterTest extends \PHPUnit_Framework_TestCase $this->assertEquals("No resource at /cats/", $captured); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testRespondWithErrorHandlerForNoRoute() + { + $_SERVER["REQUEST_URI"] = "/cats/"; + $_SERVER["HTTP_HOST"] = "localhost"; + $_SERVER["REQUEST_METHOD"] = "GET"; + + $router = new Router(); + $router->setErrorHandler(404, __NAMESPACE__ . '\\MessageHandler'); + ob_start(); + $router->respond(); + $captured = ob_get_contents(); + ob_end_clean(); + + $this->assertEquals("Not Found", $captured); + } + /** * @dataProvider nestedRouterRoutesProvider */