Commit 175a7421 by pupi1985

Avoid recreating params arrays

parent 419c30ab
...@@ -20,11 +20,25 @@ namespace Q2A\Http; ...@@ -20,11 +20,25 @@ namespace Q2A\Http;
class Router class Router
{ {
/** @var array */
protected $routes; protected $routes;
/** @var array */
private $paramsConverterKeys;
/** @var array */
private $paramsConverterValues;
public function __construct($routeData = array()) public function __construct($routeData = array())
{ {
$this->routes = $routeData; $this->routes = $routeData;
$paramsConverter = array(
'{str}' => '([^/]+)',
'{int}' => '([0-9]+)',
);
$this->paramsConverterKeys = array_keys($paramsConverter);
$this->paramsConverterValues = array_values($paramsConverter);
} }
public function addRoute($id, $httpMethod, $routePath, $class, $func) public function addRoute($id, $httpMethod, $routePath, $class, $func)
...@@ -34,7 +48,7 @@ class Router ...@@ -34,7 +48,7 @@ class Router
public function match($request) public function match($request)
{ {
foreach ($this->routes as $id=>$route) { foreach ($this->routes as $id => $route) {
if (count($route) !== 4) { if (count($route) !== 4) {
continue; continue;
} }
...@@ -45,17 +59,27 @@ class Router ...@@ -45,17 +59,27 @@ class Router
continue; continue;
} }
$pathRegex = '#^' . str_replace(array('{str}', '{int}'), array('([^/]+)', '([0-9]+)'), $routePath) . '$#'; $pathRegex = $this->buildPathRegex($routePath);
if (preg_match($pathRegex, $request, $matches)) { if (preg_match($pathRegex, $request, $matches)) {
return array( return array(
'id' => $id, 'id' => $id,
'controller' => $callClass, 'controller' => $callClass,
'function' => $callFunc, 'function' => $callFunc,
'params' => array_slice($matches, 1) 'params' => array_slice($matches, 1),
); );
} }
} }
return false; return false;
} }
/**
* @param $routePath
*
* @return string
*/
private function buildPathRegex($routePath)
{
return '#^' . str_replace($this->paramsConverterKeys, $this->paramsConverterValues, $routePath) . '$#';
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment