Example #1
0
 /**
  * Uses input to parse added routes, then matches them using matcher and finally returns
  * result using dispatcher.
  *
  * @return array|mixed Default dispatcher returns an array, custom ones can return anything
  */
 public function __invoke()
 {
     if (!is_null($this->response)) {
         return $this->response;
     }
     $this->input->parse();
     $command = $this->input->command();
     if (empty($command) || !isset($this->routes[$command])) {
         return $this->dispatcher->error(false, [self::COMMAND], $this->input);
     }
     /** @var \SplQueue $queue */
     $queue = $this->routes[$command];
     $error = true;
     while (!$queue->isEmpty() && !empty($error)) {
         /** @var \Toobo\SeaLion\Route\RouteInterface $route */
         /** @var mixed $handler */
         list($route, $handler) = $queue->dequeue();
         $all = [self::ARGUMENTS, self::OPTIONS, self::FLAGS];
         /** @var array $matched */
         $matched = $this->matcher->match($route, $this->input);
         /** @var array $notMatched */
         $notMatched = array_values(array_diff($all, $matched));
         $error = empty($notMatched) ? null : $this->dispatcher->error($command, $notMatched, $this->input);
         $this->errors[] = $error;
     }
     if (is_null($error)) {
         $this->errors = [];
         $this->response = $this->dispatcher->success($command, $handler, $this->input);
     } else {
         $this->response = $error;
     }
     return $this->response;
 }