Optimized for static routes

This commit is contained in:
Phil 2015-01-01 19:44:33 +00:00
parent a384a65346
commit b0c1330a26
2 changed files with 57 additions and 23 deletions

View File

@ -14,6 +14,7 @@ use pjdietz\WellRESTed\Exceptions\HttpExceptions\HttpException;
use pjdietz\WellRESTed\Interfaces\HandlerInterface; use pjdietz\WellRESTed\Interfaces\HandlerInterface;
use pjdietz\WellRESTed\Interfaces\RequestInterface; use pjdietz\WellRESTed\Interfaces\RequestInterface;
use pjdietz\WellRESTed\Interfaces\ResponseInterface; use pjdietz\WellRESTed\Interfaces\ResponseInterface;
use pjdietz\WellRESTed\Routes\StaticRoute;
/** /**
* Router * Router
@ -43,6 +44,11 @@ class Router implements HandlerInterface
*/ */
public function getResponse(RequestInterface $request, array $args = null) public function getResponse(RequestInterface $request, array $args = null)
{ {
$path = $request->getPath();
if (array_key_exists($path, $this->routes)) {
$handler = new $this->routes[$path]();
$response = $handler->getResponse($request, $args);
} else {
foreach ($this->routes as $route) { foreach ($this->routes as $route) {
/** @var HandlerInterface $route */ /** @var HandlerInterface $route */
try { try {
@ -52,6 +58,9 @@ class Router implements HandlerInterface
$response->setStatusCode($e->getCode()); $response->setStatusCode($e->getCode());
$response->setBody($e->getMessage()); $response->setBody($e->getMessage());
} }
if ($response) break;
}
}
if ($response) { if ($response) {
// Check if the router has an error handler for this status code. // Check if the router has an error handler for this status code.
$status = $response->getStatusCode(); $status = $response->getStatusCode();
@ -67,7 +76,6 @@ class Router implements HandlerInterface
} }
return $response; return $response;
} }
}
return null; return null;
} }
@ -78,8 +86,15 @@ class Router implements HandlerInterface
*/ */
public function addRoute(HandlerInterface $route) public function addRoute(HandlerInterface $route)
{ {
if ($route instanceof StaticRoute) {
$handler = $route->getHandler();
foreach ($route->getPaths() as $path) {
$this->routes[$path] = $handler;
}
} else {
$this->routes[] = $route; $this->routes[] = $route;
} }
}
/** /**
* Append a series of routes. * Append a series of routes.

View File

@ -64,4 +64,23 @@ class StaticRoute extends BaseRoute
return null; return null;
} }
/**
* Returns the target class this maps to.
*
* @return HandlerInterface
*/
public function getHandler()
{
return $this->getTarget();
}
/**
* Returns the paths this maps to a target handler.
*
* @return array Array of paths.
*/
public function getPaths()
{
return $this->paths;
}
} }