Example #1
0
 /**
  * @param Request $req
  * @param Response $res
  * @return mixed
  * @throws NotFoundException
  */
 public function handle(Request &$req, Response &$res)
 {
     $url = $this->getCleanUrl($req->getUri());
     $urlParams = $this->getCleanUrlParameters($url);
     $urlParamsCount = count($urlParams);
     $handler = null;
     $methodGroup = $this->handlers[$req->getMethod()];
     if (count($methodGroup) == 0) {
         throw new NotFoundException("Unable to find any handlers.");
     }
     if (isset($methodGroup[$url])) {
         $handler = $methodGroup[$url];
     } else {
         foreach ($methodGroup as $key => $value) {
             $keyParams = array();
             preg_match_all("/\\{([\\w+]+)\\}/", $key, $keyParams);
             if (count($keyParams[0]) != $urlParamsCount) {
                 continue;
             }
             for ($i = 0; $i < count($urlParams); $i++) {
                 $req->setParam($keyParams[1][$i], urldecode(explode("?", $urlParams[$i])[0]));
             }
             $handler = $value;
             break;
         }
     }
     if (!is_array($handler)) {
         throw new NotFoundException("Unable to find matching handler.");
     }
     foreach ($handler["middleware"] as $middleware) {
         /**
          * @var $middleware IMiddleware
          */
         $middleware->handle($req, $res);
     }
     if (!is_callable($handler["handler"])) {
         throw new NotFoundException("Handler is malformed.");
     }
     return $handler["handler"]($req, $res);
 }