Run middleware

@param \Modulus\Http\Request $request
@param object $route
@param string $group
@param array $all
@return void
437694
public static function run($request, object $route, string $group, array $all = [])
  {
    foreach ($route->middleware as $value) {
      if (isset(HttpFoundation::$routeMiddleware[explode(':', $value)[0]]) || class_exists($value)) {
        $all[] = $value;
      }
    }

    $first = isset(HttpFoundation::$middlewareGroup[
      isset($route->middleware[0]) ? $route->middleware[0] : null
    ]) ? true : null;

    if ($first) {
      $middlwares = array_merge(HttpFoundation::$middlewareGroup[$route->middleware[0]] ?? [], $all);
    } else {
      $middlwares = $all;
    }

    $middlwares = array_merge(HttpFoundation::$middleware, $middlwares);

    foreach($middlwares as $middleroute) {
      $attributes = [];

      if (isset(HttpFoundation::$routeMiddleware[explode(':', $middleroute)[0]])) {
        $route = explode(':', $middleroute);

        if (count($route) > 1) {
          $attributes = explode(',', explode(':', $middleroute)[1]);
        }

        $middleroute = HttpFoundation::$routeMiddleware[explode(':', $middleroute)[0]];
      }

      if ((new $middleroute)->handle($request, true, $attributes) == false) {
        exit;
      }
    }
  }
819928
public function dispatch($route, $all = false, $redirect = true)
    {
        $route = urldecode($route);

        // Fetch page if there's a defined route to it.
        $page = isset($this->routes[$route]) ? $this->get($this->routes[$route]) : null;
        // Try without trailing slash
        if (!$page && Utils::endsWith($route, '/')) {
            $page = isset($this->routes[rtrim($route, '/')]) ? $this->get($this->routes[rtrim($route, '/')]) : null;
        }

        // Are we in the admin? this is important!
        $not_admin = !isset($this->grav['admin']);

        // If the page cannot be reached, look into site wide redirects, routes + wildcards
        if (!$all && $not_admin) {

            // If the page is a simple redirect, just do it.
            if ($redirect && $page && $page->redirect()) {
                $this->grav->redirectLangSafe($page->redirect());
            }

            // fall back and check site based redirects
            if (!$page || ($page && !$page->routable())) {
                /** @var Config $config */
                $config = $this->grav['config'];

                // See if route matches one in the site configuration
                $site_route = $config->get("site.routes.{$route}");
                if ($site_route) {
                    $page = $this->dispatch($site_route, $all);
                } else {

                    /** @var Uri $uri */
                    $uri = $this->grav['uri'];
                    /** @var \Grav\Framework\Uri\Uri $source_url */
                    $source_url = $uri->uri(false);

                    // Try Regex style redirects
                    $site_redirects = $config->get('site.redirects');
                    if (is_array($site_redirects)) {
                        foreach ((array)$site_redirects as $pattern => $replace) {
                            $pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#';
                            try {
                                $found = preg_replace($pattern, $replace, $source_url);
                                if ($found !== $source_url) {
                                    $this->grav->redirectLangSafe($found);
                                }
                            } catch (ErrorException $e) {
                                $this->grav['log']->error('site.redirects: ' . $pattern . '-> ' . $e->getMessage());
                            }
                        }
                    }

                    // Try Regex style routes
                    $site_routes = $config->get('site.routes');
                    if (is_array($site_routes)) {
                        foreach ((array)$site_routes as $pattern => $replace) {
                            $pattern = '#^' . str_replace('/', '\/', ltrim($pattern, '^')) . '#';
                            try {
                                $found = preg_replace($pattern, $replace, $source_url);
                                if ($found !== $source_url) {
                                    $page = $this->dispatch($found, $all);
                                }
                            } catch (ErrorException $e) {
                                $this->grav['log']->error('site.routes: ' . $pattern . '-> ' . $e->getMessage());
                            }
                        }
                    }
                }
            }
        }

        return $page;
    }
337083
public function run($group = '')
    {
        if (!empty($this->validation_data) || $this->CI->input->method() === 'post') {
            $this->ran = true;
            return parent::run($group);
        }
        return false;
    }
703406
protected function run(Request $request)
	{
		// If there's nothing to dispatch, continue along the middleware pipeline
		$handler = $request->getAttribute('dispatch.handler', false);
		if ($handler === false) {
			return $this->chain($request);
		}

		// Setup any remaining chained parts of the dispatch for future dispatch
		$request = $request->withAttribute('dispatch.handler', $this->resolver->shift($handler));

		// Resolve the handler into something callable
		$dispatchable = $this->resolver->resolve($handler, $resolutionType);

		// Dispatch
		$parameters = [
			$dispatchable,
			$resolutionType,
			DispatchAdaptorInterface::SOURCE_DISPATCH_MIDDLEWARE,
			$request
		];
		$response = $this->getResponseObject();
		if ($response !== null) {
			$parameters[] = $response;
		}
		return $this->dispatcher->dispatch(...$parameters) ?: $this->chain($request);
	}
481518
protected function setFoundMiddleware(Route $route) : void
    {
        if (is_null($route->getStrategy())) {
            $route->setStrategy($this->getStrategy());
        }

        // wrap entire dispatch process in exception handler
        $this->prependMiddleware($route->getStrategy()->getExceptionHandler());

        // add group and route specific middleware
        if ($group = $route->getParentGroup()) {
            $this->middlewares($group->getMiddlewareStack());
        }

        $this->middlewares($route->getMiddlewareStack());

        // add actual route to end of stack
        $this->middleware($route);
    }
799988
protected function appendGroupInfo(Route $route): void
    {
        $path = $bak = $route->getPath();

        // Always add '/' prefix.
        $path = \strpos($path, '/') === 0 ? $path : '/' . $path;
        $path = $this->currentGroupPrefix . $path;

        // Has setting 'ignoreLastSlash'
        if ($path !== '/' && $this->ignoreLastSlash) {
            $path = \rtrim($path, '/');
        }

        // Not in group and path not change.
        if ($bak === $path) {
            return;
        }

        $route->setPath($path);

        // Not in group
        if (!$this->currentGroupPrefix) {
            return;
        }

        if ($this->currentGroupOption) {
            $route->setOptions(\array_merge($this->currentGroupOption, $route->getOptions()));
        }

        // Prepend group middleware at before.
        if ($this->currentGroupChains) {
            $route->setChains(\array_merge($this->currentGroupChains, $route->getChains()));
        }
    }
296136
public function group()
    {
        $args = func_get_args();
        $route = array_shift($args);
        $callable = array_pop($args);
        if (is_string($route) && is_callable($callable)) {
            call_user_func($callable, $route);
        }
    }
121834
final public function run(Request $request)
    {
        $this->request = $request;
        $path = $this->request->getUri()->getPath();
        $this->requestedUri = ($path != "/") ? rtrim($path, "/") : "/";
        $this->requestedMethod = strtoupper($this->request->getMethod());
        $this->requestedRepresentation = $this->request->getAccept();
        $this->verifyRequestMethod();
        $route = $this->findRouteFromRequest();
        $this->prepareResponse($route);
    }
859931
private function executeRouteMiddleware(Route &$route, $position, $method)
    {
        $method = strtoupper($method);

        /** @var Middleware[] $middleware */
        $middleware = array();
        $continue   = true;

        // Get all global middleware's.
        if (isset(
                $this->middleware['global'],
                $this->middleware['global'][$position])
            && count($this->middleware['global'][$position]) > 0) {

            $middleware = array_merge($middleware, $this->middleware['global'][$position]);
        }

        // Group middleware if defined.
        if ($route->getGroup() !== null
            &&  isset($this->middleware[$route->getGroup()],
                $this->middleware[$route->getGroup()][$position])
            && count($this->middleware[$route->getGroup()][$position]) > 0) {
            $middleware = array_merge($middleware, $this->middleware[$route->getGroup()][$position]);
        }


        // Will execute all middleware in order..:
        foreach ($middleware as $trigger)
        {
            if (count($trigger->getMethods()) === 0
            ||  in_array(strtoupper($method), $trigger->getMethods())) {

                if ($this->executeMiddleware($trigger) === false) {
                    $continue = false;
                }
            }
        }

        return $continue;
    }
766626
public function run($group, $module, $model, $type = "", $mode = "default", $output = "view", $file = "", $customTemplate = "")
    {
        switch ($type)
        {
            case "controller":
                $this->generateController($group, $module, $model, $mode, $output, $file, $customTemplate);
                $this->generateRoute($group, $module, $model, $mode, $output, $file, $customTemplate);
                break;
            case "model":
                $this->generateModel($group, $module, $model, $mode, $output, $file, $customTemplate);
                break;
            case "repository":
                $this->generateRepository($group, $module, $model, $mode, $output, $file, $customTemplate);
                break;
            case "view":
                $this->generateView($group, $module, $model, $mode, $output, $file, $customTemplate);
                break;
            default:
                $this->generateController($group, $module, $model, $mode, $output, $file, $customTemplate);
                $this->generateRoute($group, $module, $model, $mode, $output, $file, $customTemplate);
                $this->generateModel($group, $module, $model, $mode, $output, $file, $customTemplate);
                $this->generateRepository($group, $module, $model, $mode, $output, $file, $customTemplate);
                $this->generateView($group, $module, $model, $mode, $output, $file, $customTemplate);
        }
    }
1090233
protected function runRouteWithinStack(Route $route, Request $request)
    {
        $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
                                $this->container->make('middleware.disable') === true;

        $middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddleware($route);

        return (new Pipeline($this->container))
                        ->send($request)
                        ->through($middleware)
                        ->then(function ($request) use ($route) {
                            return $this->prepareResponse(
                                $request, $route->run()
                            );
                        });
    }
692429
public function run( string $routesFilename=''  )
  {
    #
    # Load the Routes
    #
    if ( empty($routesFilename) ) {
      $routesFilename = $this->getBasePath().'/app/Config/routes.json';
    }
    $this->loadRoutes( $routesFilename );


    # Get Method and URI
    $httpMethod = $this->getRequest()->getMethod();
    $path = $this->getRequest()->getUri()->getPath();
    $routeInfo = null;

    # Find route match in groups
    foreach ($this->getRouteGroups() as $routeGroup)
    {
      # Match the METHOD and URI to the routes in this group
      $routeInfo = $routeGroup->matchRoute($httpMethod,$path);

      if ( count($routeInfo)>0 ) {
        $beforeResult = true; // assume all before handlers succeed
        $routeResult = false;
        $afterResult = true; // assume all after handlers succeed

        # Debug log
        $this->getLogger()->debug('Route matched ',['handler'=>$routeInfo['handler']]);

        #
        # Run the Common AND Groups Before Middlewares (ServerRequestInterface)
        #
        $beforeMiddleware = array_merge($this->beforeMiddleware, $routeGroup->getBeforeMiddleware());

        foreach ($beforeMiddleware as $middleware)
        {
          if (class_exists($middleware) ) {
            $beforeHandler = new $middleware($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Running Before middleware',['rid'=>app('requestId'),'middleware'=>$middleware]);

            if (!$beforeHandler->handle($routeInfo['args'])) {
              # Record outcome
              $beforeResult = false;
              # Stop processing more middleware
              break;
            }
          } else {
            # Log
            $this->getLogger()->warning('Before Middleware not found',['rid'=>app('requestId'),'middleware'=>$middleware]);
          }
        }

        #
        # Create & Run the Handler Class - If the Before Middlewares where ok!
        #
        if ($beforeResult) {
          # Extract class & method
          $arr = explode('@',$routeInfo['handler']);
          $handlerClass = $arr[0];
          $handlerMethod = ($arr[1] ?? 'handle');

          # Check existance of handler class
          if (class_exists($handlerClass))
          {
            # Create the class
            $routeHandler = new $handlerClass( $routeInfo['args'] );

            # Check method existance
            if ($routeHandler && method_exists($routeHandler,'initialize') && method_exists($routeHandler,$handlerMethod))
            {
              # Debug log
              $this->getLogger()->debug('Running controller->initialize()',['rid'=>app('requestId'),'controller'=>$handlerClass]);

              # Initialize
              $routeHandler->initialize($routeInfo['args']);

              # Debug log
              $this->getLogger()->debug('Running controller->handle()',['rid'=>app('requestId'),'method'=>$handlerMethod]);

              # Run handler
              $routeResult = $routeHandler->$handlerMethod($routeInfo['args']);
            } else {
              # Log
              $this->getLogger()->error('Method not found in controller ',['rid'=>app('requestId'),'controller'=>$handlerClass,'method'=>$handlerMethod]);
            }
          } else {
            # Debug log
            $this->getLogger()->debug('Controller not found ',['rid'=>app('requestId'),'controller'=>$handlerClass]);
          }
        }

        #
        # Run the After Middlewares (ServerRequestInterface)
        #
        $afterMiddleware = array_merge($this->afterMiddleware,$routeGroup->getAfterMiddleware());
        foreach ($afterMiddleware as $middleware)
        {
          if (class_exists($middleware) ) {
            $afterHandler = new $middleware($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Running After middleware',['rid'=>app('requestId'),'middleware'=>$middleware]);

            if (!$afterHandler->handle($routeInfo['args'])) {
              return false;
            }
          } else {
            # Log
            $this->getLogger()->warning('After Middleware not found',['rid'=>app('requestId'),'middleware'=>$middleware]);
          }
        }

        return $routeResult;

      } else {
        # No route matched the URI in this group, we'll look in the next group or exit the foreach()
        $routeInfo = null;
      }

    }

    # Output debug info
    if (is_null($routeInfo)) {
      # Debug log
      $this->getLogger()->debug('No route matched request',['rid'=>app('requestId'),'method'=>$httpMethod,'path'=>$path]);
    }

    return false; // default response
  }
174505
protected function runRoute(Request $request, Route $route)
    {
        $request->setRouteResolver(function () use ($route) {
            return $route;
        });

        $this->events->dispatch(new Events\RouteMatched($route, $request));

        return $this->prepareResponse($request,
            $this->runRouteWithinStack($route, $request)
        );
    }
158576
public function apply(Request $request, Match $match, array $middlewares = [])
    {
        // get the pipe of route selected by router
        $pipe = $match->getOption('pipe');

        // check if pipe is valid
        if (!is_array($pipe)) {
            // early return
            return $this->resolve($request, $match);
        }
        // filter the middlewares using the pipe of match
        $piping = array_filter($middlewares, function ($middleWare) use ($pipe) {
            // check if alias of middleware is in pipe
            return in_array($middleWare->alias(), $pipe);
        });

        // check if exists valid middlewares
        if (!count($piping)) {
            // early return
            return $this->resolve($request, $match);
        }

        // inject the handler into the HttpResponse middleware
        $that = $this;
        $piping[] = new HttpResponse(function () use ($that, $request, $match) {
            // resolve the request using the match
            return $that->resolve($request, $match);
        });

        // create a delegate with the middlewares
        $delegate = new Delegate($piping);

        // start the pipe
        return $delegate->process($request);
    }
323421
public function run($route, $params = [])
    {
        $this->scanner->stdout('Detect PhpFunction - BEGIN', Console::FG_CYAN);
        foreach (self::$files[static::EXTENSION] as $file) {
            if ($this->containsTranslator($this->module->phpTranslators, $file)) {
                $this->extractMessages($file, [
                    'translator' => (array) $this->module->phpTranslators,
                    'begin' => '(',
                    'end' => ')',
                ]);
            }
        }

        $this->scanner->stdout('Detect PhpFunction - END', Console::FG_CYAN);
    }
482555
public function launch(Request $request, Response $response)
    {
        if (count($this->routes) === 0) {
            throw new \RuntimeException("No routes defined");
        }

        $this->uri = $request->httpRequest->getPath();

        if ($this->uri = null) {
            $this->uri = "/";
        }

        $request->on('end', function () use (&$request, &$response) {
            $this->matchRoutes($request, $response);  
        });

        $request->on('error', function ($error) use (&$request, &$response) {
            $this->emit('error', [$request, $response, $error]);
        });

        $request->parseData();
    }
6115
public function trackMatchedRoute(Route $route, Request $request)
    {
        if ( ! $this->isEnabled()) return;

        $tracker = $this->getRouteTracker();

        if ($tracker->isTrackable($route)) {
            $this->mergeVisitorActivityData([
                'route_path_id' => $tracker->track($route, $request),
            ]);
        }
        else
            $this->disable();
    }