public function match($request) { $this->request = '/' . trim($request, '/'); $query = $this->getQuery(); $format = $this->matchFormat(); $data = array('name' => null, 'action' => null, 'route' => null, 'format' => $format, 'query' => $query); foreach ($this->routes as $name => $route) { $route = $this->prepareRoute($route); if (empty($route['route'])) { continue; } $params = UrlBuilder::getRouteParams($route); $regexp = $this->getRouteRegexp($route['route'], $params); // reduce verbose description of params to just default value: $params = array_map(function ($x) { return $x['default']; }, $params); if (preg_match(sprintf('/^%s$/', $regexp), $this->request, $match)) { foreach ($match as $key => $value) { if (!is_numeric($key)) { $params[$key] = $value; } } $data['route'] = $route; $data['name'] = $name; $data['action'] = $route['action']; $data['params'] = $params + $query; return $data; } } // TODO: maybe a dedicated exception or just null? throw new \Exception("No route found for request: {$this->request}"); }
<?php require 'vendor/autoload.php'; use Nassau\Config\Config, Nassau\Routing\Matcher, Nassau\Routing\UrlBuilder; $routes = new Config('etc/routes.yaml'); $routing = new Matcher($routes); $builder = new UrlBuilder($routes); foreach (array('plan/1', 'plan/xxx', 'plan/1/edit', '/plan/xxx/edit', 'plan/1/cost', 'plan/1/cost/2012-03-03', 'plan/1/cost/2010', 'log', 'log.html', '/log/1', 'zarzadzaj', 'raport?a=b') as $request) { try { $m = $routing->match($request); $url = $builder->build($m['name'], array("filter" => rand(1, 10)) + $m['params']); echo implode(' => ', array($request, $url, $m['name'], print_r($m['params'], true))); } catch (Exception $E) { echo $E->getMessage() . "\n"; } } echo "\n\n";