/** * Adds a route to the collection. * * The syntax used in the $route string depends on the used route parser. * * @param string|string[] $methods * @param string $route * @param mixed $handler * @return self */ public function add($name, $methods, $pattern, $handler) { $route = new Route(); if (!empty($name)) { $names = array_merge($this->groupNames, [$name]); $route->setName($names); $name = $route->getName(); if (array_key_exists($name, $this->nameToRoute)) { throw new Exception("Route with name \"{$name}\" already exists"); } $this->nameToRoute[$name] = $route; } $patterns = array_merge($this->groupPatterns, [$pattern]); $route->setPath($patterns); $route->setMethod($methods); $route->setHandler($handler); $routeDatas = $this->parse($route->getPath()); foreach ($routeDatas as $routeData) { if ($this->isStaticRoute($routeData)) { $this->addStaticRoute($routeData, $route); } else { $this->addVariableRoute($routeData, $route); } } return $this; }
/** * @param $path string * @param $action callable|string */ public static function post($path, $action) { $route = new Route(); $route->setMethod("GET"); $route->setPath($path); $route->setAction($action); self::addRoute($route); }
public function testMatchMethod() { // all $route = new Route("/"); $this->assertTrue($route->matchMethod("GET")); $this->assertTrue($route->matchMethod("HEAD")); $this->assertTrue($route->matchMethod("POST")); $this->assertTrue($route->matchMethod("PUT")); $this->assertTrue($route->matchMethod("DELETE")); $this->assertTrue($route->matchMethod("OPTIONS")); $this->assertTrue($route->matchMethod("get")); $this->assertTrue($route->matchMethod("post")); // GET $route->setMethod("GET"); $this->assertTrue($route->matchMethod("GET")); $this->assertTrue($route->matchMethod("get")); $this->assertFalse($route->matchMethod("POST")); $this->assertFalse($route->matchMethod("put")); // POST $route->setMethod("post"); $this->assertTrue($route->matchMethod("POST")); $this->assertTrue($route->matchMethod("post")); $this->assertFalse($route->matchMethod("GET")); $this->assertFalse($route->matchMethod("put")); }