PHPRouter\Router::match PHP Method

match() public method

Match given request _url and request method and see if a route has been defined for it If so, return route's target If called multiple times
public match ( string $requestUrl, string $requestMethod = 'GET' ) : boolean | Route
$requestUrl string
$requestMethod string
return boolean | Route
    public function match($requestUrl, $requestMethod = 'GET')
    {
        foreach ($this->routes->all() as $routes) {
            // compare server request method with route's allowed http methods
            if (!in_array($requestMethod, (array) $routes->getMethods())) {
                continue;
            }
            $currentDir = dirname($_SERVER['SCRIPT_NAME']);
            if ($currentDir != '/') {
                $requestUrl = str_replace($currentDir, '', $requestUrl);
            }
            $route = rtrim($routes->getRegex(), '/');
            $pattern = "@^{$this->basePath}{$route}/?\$@i";
            if (!preg_match($pattern, $requestUrl, $matches)) {
                continue;
            }
            $matchedText = array_shift($matches);
            $params = array();
            if (preg_match_all("/:([\\w-%]+)/", $routes->getUrl(), $argument_keys)) {
                // grab array with matches
                $argument_keys = $argument_keys[1];
                // check arguments number
                if (count($argument_keys) != count($matches)) {
                    continue;
                }
                // loop trough parameter names, store matching value in $params array
                foreach ($argument_keys as $key => $name) {
                    if (isset($matches[$key])) {
                        $params[$name] = $matches[$key];
                    }
                }
            }
            $routes->setParameters($params);
            $routes->dispatch();
            return $routes;
        }
        return false;
    }

Usage Example

示例#1
0
 /**
  * @covers Router::match
  * @covers Route::getParameters
  */
 public function testParamsWithDynamicFilterMatch()
 {
     $collection = new RouteCollection();
     $route = new Route('/js/:filename.js', array('_controller' => 'PHPRouter\\Test\\SomeController::dynamicFilterUrlMatch', 'methods' => 'GET'));
     $route->setFilters(array(':filename' => '([[:alnum:]\\.]+)'), true);
     $collection->attachRoute($route);
     $router = new Router($collection);
     $this->assertEquals(array(array('filename' => 'someJsFile')), $router->match('/js/someJsFile.js')->getParameters());
     $this->assertEquals(array(array('filename' => 'someJsFile.min')), $router->match('/js/someJsFile.min.js')->getParameters());
     $this->assertEquals(array(array('filename' => 'someJsFile.min.js')), $router->match('/js/someJsFile.min.js.js')->getParameters());
 }