Use registered 404 error handler when no route matches in Router::respond

This commit is contained in:
PJ Dietz 2015-01-21 09:51:14 -05:00
parent ca2c8625ec
commit 1a88e0273d
2 changed files with 44 additions and 10 deletions

View File

@ -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]();
}

View File

@ -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
*/