Invoke given route. If the route is null, returns a 404 response.

@param IRoute $route

@return IHttpResponse
@throws InvalidRouteValue
422024
public function invoke($route) {
        if ($route instanceof IRoute) {
            return $this->invokeRoute($route);
        }

        return new HttpResponse(HttpStatusCode::NOT_FOUND);
    }
163273
private function createResponse($route): ?Response
    {
        $controller = $this->getRouteControllerInstance($route);
        if (!is_null($controller)) {
            $responseBefore = $controller->before();
            if ($responseBefore instanceof Response) {
                return $responseBefore;
            }
        }

        $values = $route['route']->getArguments($this->requestedUri);
        $this->loadRequestParameters($values);
        $callback = new Callback($route['callback']);
        $arguments = $this->getFunctionArguments($callback->getReflection(), array_values($values));
        $response = $callback->executeArray($arguments);

        if (!is_null($controller)) {
            $responseAfter = $controller->after($response);
            if ($responseAfter instanceof Response) {
                return $responseAfter;
            }
        }
        return $response;
    }
1171591
public function redirectToRouteAction(Request $request, $route, $permanent = false)
    {
        if ('' === $route) {
            throw new HttpException($permanent ? 410 : 404);
        }

        $attributes = array_merge($request->attributes->get('_route_params'), $request->query->all());
        unset($attributes['route'], $attributes['permanent']);

        return new RedirectResponse(
            $this->container->get('router')->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL),
            $permanent ? 301 : 302,
            ['Cache-Control' => 'private']
        );
    }
270689
public function callRouteBefore($route, $request)
	{
		$response = $this->callPatternFilters($route, $request);

		return $response ?: $this->callAttachedBefores($route, $request);
	}
454544
public function setRoute(RouteInterface $route): RouterInterface
    {
        $regexp = $route->getRegexp();
        $this->_routes[$regexp] = $route;
        return $this;
    }
99689
public function controller($route, ...$args) {
		// Sanitize the call
		$route = preg_replace('/[^a-zA-Z0-9_\/]/', '', (string)$route);

		// Keep the original trigger
		$trigger = $route;

		// Trigger the pre events
		$result = $this->registry->get('event')->trigger('controller/' . $trigger . '/before', array(&$route, &$args));

		// Make sure its only the last event that returns an output if required.
		if ($result != null && !$result instanceof Exception) {
			$output = $result;
		} else {
			$action = new Action($route);
			$output = $action->execute($this->registry, $args);
		}

		// Trigger the post events
		$result = $this->registry->get('event')->trigger('controller/' . $trigger . '/after', array(&$route, &$args, &$output));

		if ($result && !$result instanceof Exception) {
			$output = $result;
		}

		if (!$output instanceof Exception) {
			return $output;
		}
	}
433932
private static function runRouteMiddleware($route)
    {
        $routeMiddleware = Filter::$routeMiddleware;

        if (!is_null($route->getMiddleware())) {
            // if ($route->getMiddleware()['type'] == 'route' && ! is_null($route->getMiddleware()['middlewares'])) {
            foreach ($route->getMiddleware() as $middleware) {
                //Check if the routes middlewares are in filter class
                exception_if(!array_has($routeMiddleware, $middleware), RouteMiddlewareNotFoundException::class, $middleware);

                $middleware = instance($routeMiddleware[$middleware]);

                $middleware->handle(new Request());
            }
        }

        return true;
    }
1180450
protected function redirectToRoute(string $route, $parameters = [], int $status = 302): RedirectResponse
    {
        return $this->redirect($this->generateUrl($route, $parameters), $status);
    }
239588
protected function getProtocolForRoute(Route $route)
    {
        $protocolId = $route->getDefault(Protocol::OPTION_PROTOCOL);
        if (!$protocolId) {
            throw new InvalidConfigurationException(sprintf(
                'Route "%s" has no protocol defined',
                $route->getPath()
            ));
        }

        $protocolId = substr($protocolId, 1);

        return [$protocolId, $this->getContainer()->get($protocolId)];
    }
1144264
private function handleMatchingRoute(CalledUri $calledUri, Route $route): UriResource
    {
        if ($route->requiresAuth()) {
            return new ProtectedResource(
                $route->authConstraint(),
                $this->resolveResource($calledUri, $route),
                $this->injector
            );
        }

        return $this->resolveResource($calledUri, $route);
    }
502990
protected function generateRouteUrl($route = null)
    {
        if (null === $route || strpos($route, '/') !== 0) {
            return $route;
        }

        if (null === $this->getRouteMatch()) {
            throw new Exception\RuntimeException('No RouteMatch instance provided');
        }

        $routeName = $this->getRouteMatch()->getMatchedRouteName();

        if ($routeName === null) {
            throw new Exception\RuntimeException('RouteMatch does not contain a matched route name');
        }

        $position = strpos($routeName, '/');

        if ($position !== false) {
            /**
             * If we request the name /, it will mean that we need to only get
             * the root part of the route without any other module route params
             */
            if ('/' === $route) {
                $results = substr($routeName, 0, $position);
            } else {
                $results = substr($routeName, 0, $position) . $route;
            }
        } else {
            if ('/' === $route) {
                $results = $routeName;
            } else {
                $results = $routeName . $route;
            }
        }

        return $results;
    }
1244354
protected function dispatchMethod($request, $route)
    {
        list($path, $var) = $this->parseUrlPath($route);

        $route = str_replace('/', '@', implode('/', $path));
        $method = strpos($route, '@') ? explode('@', $route) : $route;

        return new CallbackDispatch($request, $this, $method, $var);
    }
996893
@Override
    public Result call(final Route route, final RequestContext context) throws Exception {
        URI redirectedURI = rewriteURI(context.request());
        logger.debug("Redirecting request - rewriting {} to {}", context.request().uri(), redirectedURI);
        if (redirectedURI == null) {
            return onRewriteFailed(context);
        }
        return Results.redirect(redirectedURI.toString());
    }
14984
public function createRoute(IRouter $routes, string $url): void
	{
		$this->createPageRoute($routes, $url);
		$this->createDefaultPageRoutes($routes, $url);
	}
260231
public function handle(RouteInterface $route)
    {
        $params = [];

        // create the regex that matches paths against the route
        $patternRegex = $this->createRouteRegex($route, $route->getPattern(), $params);

        // if the route regex matches the current request path
        if (preg_match($patternRegex, $route->getRoute(), $matches)) {
            if (count($matches) > 1) {
                // remove the first match (which is the full route match)
                array_shift($matches);

                // use the extracted parameters as the arguments' keys and the matches as the arguments' values
                return array_combine($params, $matches);
            } else {
                return [];
            }
        }
        // if the route regex does not match the current request path returns null
    }
902724
public function redirectTo($route = null)
    {
        if (is_null($route)) {
            $url = $this->di->request->getCurrentUrl();
        } else {
            $url = $this->di->url->create($route);
        }
        $this->di->response->redirect($url);
    }
516781
public function dispatch(\Parable\Routing\Route $route)
    {
        $this->dispatchedRoute = $route;

        $this->hook->trigger(self::HOOK_DISPATCH_BEFORE, $route);
        $controller = null;

        // Start output buffering and set $returnContent to null
        $returnContent = null;
        $this->response->startOutputBuffer();

        // Build the parameters array
        $parameters = [];
        foreach ($route->getValues() as $value) {
            $parameters[] = $value;
        }

        // Call the relevant code
        if ($route->hasControllerAndAction()) {
            $controller = \Parable\DI\Container::get($route->getController());
            $returnContent = $controller->{$route->getAction()}(...$parameters);
        } elseif ($route->hasCallable()) {
            $callable = $route->getCallable();
            $returnContent = $callable(...$parameters);
        }

        $this->hook->trigger(self::HOOK_DISPATCH_TEMPLATE_BEFORE, $route);

        // If the route has no template path, attempt to build one based on controller/action.phtml
        if (!$route->hasTemplatePath() && $route->hasControllerAndAction()) {
            $reflection = new \ReflectionClass($controller);
            $controllerName = str_replace('\\', '/', $reflection->getName());
            $controllerName = str_replace('Controller/', '', $controllerName);

            $templatePathGenerated = $this->path->getDir(
                "app/View/{$controllerName}/{$route->getAction()}.phtml"
            );

            if (file_exists($templatePathGenerated)) {
                $route->setTemplatePath($templatePathGenerated);
            }
        }

        // And check again, now that we might have a magic template path
        if ($route->hasTemplatePath()) {
            $templatePath = $this->path->getDir($route->getTemplatePath());
            $this->view->setTemplatePath($templatePath);
            $this->view->render();
        }

        // If the callback or controller/action returned content, we need to handle it
        if ($returnContent) {
            if ($this->response->getOutput()->acceptsContent($returnContent)) {
                $this->response->setContent($returnContent);
            } else {
                $type   = gettype($returnContent);
                $output = get_class($this->response->getOutput());

                // Stop the output buffer we've started above and throw
                $this->response->stopOutputBuffer();
                throw new \Parable\Framework\Exception(
                    "Route returned value of type '{$type}', which output class '{$output}' cannot handle."
                );
            }
        }

        // Any rendered content was from before the returnContent was set, so we prepend it if there's any
        $renderedContent = $this->response->returnOutputBuffer();
        if ($renderedContent) {
            $this->response->prependContent($renderedContent);
        }

        $this->hook->trigger(self::HOOK_DISPATCH_TEMPLATE_AFTER, $route);
        $this->hook->trigger(self::HOOK_DISPATCH_AFTER, $route);
        return $this;
    }