/** * If the route is a string we try to find the matching controller method and run it here * If there is middleware we run that first * Uses the format Controller@method * * @param string|array $handler * @param array $vars Route variables passed along to the handler * @param Request $request * @param Response $response * * @throws RouteNoUsesException * * @return mixed */ public static function boot($handler, array $vars, Request $request, Response $response) { // Set the handler as an array with the 'uses' key if (!is_array($handler)) { $handler = ['uses' => $handler]; } // If the handler is already an array and doesn't have a uses key, throw an error if (!array_key_exists('uses', $handler)) { throw new RouteNoUsesException('The route handler array must contain a valid [uses] key.'); } $action = $handler['uses']; // If the action is a string (ie it's a controller path), run the controller if (is_string($action)) { list($class, $method) = explode('@', $action); $class = new $class(); // If middleware is defined through the router we'll add it to the controller to be run if (array_key_exists('middleware', $handler)) { $middleware = (array) $handler['middleware']; $class->addMiddleware($middleware, true); } // Run the controller middleware, and if it returns a value we'll use that $middleware = $class->runMiddleware($request, $response); if ($middleware) { return $middleware; } // Get all of the route variables and check if anything is bound to that name foreach ($vars as $key => &$var) { $var = isset(static::$boundVars[$key]) ? static::$boundVars[$key]($var) : $var; } // If it's a closure } elseif ($action instanceof Closure) { // If middleware is defined through the router we'll run it if (array_key_exists('middleware', $handler)) { $middleware = (array) $handler['middleware']; $middleware = MiddlewareRunner::run($middleware, $request, $response); if ($middleware) { return $middleware; } } } // Get all of the route variables and check if anything is bound to that name foreach ($vars as $key => &$var) { $var = isset(static::$boundVars[$key]) ? static::$boundVars[$key]($var) : $var; } // Run the appropriate method if (isset($class)) { return $class->{$method}(...array_values($vars)); } elseif ($action instanceof Closure) { return $action(...array_values($vars)); } }
/** * Run the middleware * @return mixed */ public function runMiddleware(Request $request, Response $response) { return MiddlewareRunner::run($this->middleware, $request, $response); }