To dispatch a route

@param string $method
@param string $uri

@return mixed
@throws Exception
6966
public function dispatch($method, $uri)
    {
        $routeInfo = $this->dispatcher->dispatch($method, $uri);

        if($routeInfo[0] === Dispatcher::NOT_FOUND) {

            $this->filterRequest('*', $method);

            $routeInfo = $this->dispatcher->dispatch($method, '*');

            if(!$routeInfo[0]) {
                throw new Exception("Route [ {$uri} ] not found.");
            }
        }

        if($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
            $method = $_SERVER['REQUEST_METHOD'];
            throw new Exception("[ $method ] method not allowed.");
        }

        if($routeInfo[0] === Dispatcher::FOUND) {
            $handler = $routeInfo[1];
            $params = $routeInfo[2];

            if(!empty($filterResponse = $this->filterRequest($uri, $method))) {
                return $filterResponse;
            }

            return $this->methodDispatcher($handler, $params);
        }
    }
1323128
public static function dispatch() {
        self::$_config = MRest::getConfig('routing');

        $routeData = self::_callDispatcher(self::$_config['dispatcher']);

        if (!class_exists($routeData['class']) || !(new \ReflectionClass($routeData['class']))->isInstantiable()) {
            throw new \Exception('Application class [' . $routeData['class'] . '] was not found', 404);
        }
        $class = new $routeData['class']();

        if (!is_callable([$class, $routeData['method']])) {
            throw new \Exception('Method [' . $routeData['method'] . '] not allowed', 405);
        }

        return call_user_func_array([$class, $routeData['method']], $routeData['attributes']);
    }
1115360
public function addRoute($method, $uri, $action)
    {
        $uri = strtolower($uri);
        $action = $this->parseAction($action);

        if (isset($this->groupAttributes)) {
            if (isset($this->groupAttributes['prefix'])) {
                $uri = trim($this->groupAttributes['prefix'], '/').'/'.trim($uri, '/');
            }

            $action = $this->mergeGroupAttributes($action);
        }

        $uri = '/'.trim($uri, '/');

        if (isset($action['as'])) {
            $this->namedRoutes[$action['as']] = $uri;
        }

        $this->routes[$this->identifier] = ['method' => $method, 'uri' => $uri, 'action' => $action];
        $this->identifier++;

        return $this;
    }
743128
public function resolve(Router $router, $uri, $method)
	{
		// get all register routes with the same request method
		$routes = $router->getRoutesByMethod($method);
		// remove trailing and leading slash
		$requestedUri = trim(preg_replace('/\?.*/', '', $uri), '/');
		// loop trough the posible routes
		foreach ($routes as $route) {
			$matches = array();

			// if the requested route matches one of the defined routes
			if ($route->getUrl() === $requestedUri || preg_match('~^'.$route->getUrl().'$~', $requestedUri, $matches)) {
				$argumentArray = array();
				$arguments = $this->getArguments($matches);

				// check if there route has arguments
				if (is_array($route->getArguments()) && count($route->getArguments()) > 0) {
					// loop trough all the arguments
					foreach ($route->getArguments() as $key => $argument) {
						// if the argument exists set the value
						if (isset($arguments[$key])) {
							$argumentArray[$argument] = $arguments[$key];
						} else {
							// setting the value to null should only occure when we use an optional parameter
							$argumentArray[$argument] = null;
						}
					}
				}

				return [
					'code' => Route::STATUS_FOUND,
					'handler' => $route->getAction(),
					'arguments' => $argumentArray
				];
			}
		}

		return [
			'code' => Route::STATUS_NOT_FOUND,
			'handler' => null,
			'arguments' => []
		];
	}
1084264
public function matchRoute( string $method, string $uri )
  {
    # Make dispatcher
    $dispatcher = new \FastRoute\Dispatcher\GroupCountBased($this->routeCollector->getData());

    # Dispatch the requested METHOD and URI and see if a route matches
    $routeInfo = $dispatcher->dispatch($method, $uri);

    # Examine $RouteInfo response
    switch ($routeInfo[0])
    {
      # We found a route match
      case \FastRoute\Dispatcher::FOUND:
        # URLDecode each argument
        foreach ($routeInfo[2] as $idx=>$r)
        {
          $routeInfo[2][$idx] = \urldecode($r);
        }

        # Return the Handler + args
        return [
          'method'=>$method,
          'path'=>$uri,
          'handler'=>$routeInfo[1],
          'args'=>$routeInfo[2]
        ];
        break;

      # Nothing found
      case \FastRoute\Dispatcher::NOT_FOUND:
        return [];
        break;

      # This should never happen to us ...
      case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        return [];
        break;

      # Default we return empty
      default:
        return [];
        break;
    }
  }
1056695
public function dispatch($route, $request)
    {
        $request->setParam('Closure', $route[4]);

        if(isset($route[3]) && is_string($route[3])) {
            $view = $route[3];
            $data = $route[4];
            return ['view' => [$view, $data]];
        }
        elseif(isset($route[2]) && is_string($route[2])) {
            list($controller, $method) = explode('@', $route[2]);
            return ['controller' => [$controller, $method]];
        }
        elseif(isset($route[2]) && ($route[2] instanceof Closure || get_class($route[2]) === "Closure")) {
            $function = $route[2];
            $reflectionFunction = new ReflectionFunction($function);
            $numReqParam = $reflectionFunction->getNumberOfRequiredParameters();
            if($numReqParam > count($request->getParam('Closure'))) {
                throw new Exception('Invaliding number of required parameter passed in route\'s callable function: '.$route[1]);
            }
            ob_start();
            if($request->getParam('Closure') !== false && is_array($request->getParam('Closure')) ) {
                $return = call_user_func_array($route[2], $request->getParam('Closure'));
            }
            else {
                //$function();
                throw new Exception('Invaliding parameter passed in route\'s callable function: '.$route[1]);
            }
            $output = ob_get_clean();
            return ['output' => [$output, $return]];
        }
        else {
            throw new Exception('Invaliding route is registered for: '.$route[1]);
        }
    }
341598
public function dispatch(Route $route, $controller, $method)
    {
        $parameters = $this->resolveClassMethodDependencies(
            $route->parametersWithoutNulls(), $controller, $method
        );

        if (method_exists($controller, 'callAction')) {
            return $controller->callAction($method, $parameters);
        }

        return call_user_func_array(array($controller, $method), $parameters);
    }
164363
public function map($uri, $method)
    {
        if ($uri === '/') {
            $uri = '';
        }

        $controller = $this;

        return $this->app->map(
            $this->baseUri.$uri,
            function () use ($controller, $method) {
                $params = func_get_args();
                $i = 0;
                $a = preg_replace_callback('/:(\w+)/', function($matches) use ($controller, $params, &$i) {
                    $value = @$params[$i++];
                    $controller->routeData($matches[1], $value);
                    return $value;
                }, $controller->baseUri);
                $controller->delegate($method, array_slice($params, $i));
            }
        );
    }
474518
protected function match($method, $uri)
    {
        $result = null;

        foreach ((array) $this->router->routes() as $route)
        {
            $matched = preg_match($route->regex(), $uri, $matches);

            if ($matched && $route->method() === $method)
            {
                return array($matches, $route);
            }
        }

        return $result;
    }
937903
private function getNewRequest(string $method, UriInterface $uri): RequestInterface
    {
        return $this->transport->createRequest($method, $uri);
    }
1010075
public function invoke($uri, $method, $parameters = array())
    {
        // Request URI.
        if ( ! preg_match('/^http(s)?:/', $uri))
        {
            $uri = '/'.ltrim($uri, '/');
        }

        try
        {
            // Store the original request data and route.
            $originalInput = $this->request->input();
            $originalRoute = $this->router->getCurrentRoute();

            // Masking route to allow testing with PHPUnit.
            if ( ! $originalRoute instanceof Route)
            {
                $originalRoute = new Route(new \Symfony\Component\HttpFoundation\Request());
            }

            // Create a new request to the API resource
            $request = $this->request->create($uri, strtoupper($method), $parameters);

            // Replace the request input...
            $this->request->replace($request->input());

            // Dispatch request.
            $dispatch = $this->router->dispatch($request);

            if (method_exists($dispatch, 'getOriginalContent'))
            {
                $response = $dispatch->getOriginalContent();
            }
            else
            {
                $response = $dispatch->getContent();
            }

            // Decode json content.
            if ($dispatch->headers->get('content-type') == 'application/json')
            {
                if (function_exists('json_decode') and is_string($response))
                {
                    $response = json_decode($response, true);
                }
            }

            // Restore the request input and route back to the original state.
            $this->request->replace($originalInput);


            // This method have been removed from Laravel.
            //$this->router->setCurrentRoute($originalRoute);

            return $response;
        }
        catch (NotFoundHttpException $e)
        {
            //trigger_error('Not found');
            var_dump($e->getMessage());
        }
        catch (FatalErrorException $e)
        {
            var_dump($e->getMessage());
        }
    }
423704
public function match($uri = null, $method = null)
    {
        $context = $this->_context;

        $uri = $uri ?: $this->getRewriteUri();

        if ($method === null) {
            $method = $this->request->getServer('REQUEST_METHOD');
        }

        $context->controller = null;
        $context->action = null;
        $context->params = [];

        $context->matched = false;

        if ($this->_prefix) {
            if (strpos($uri, $this->_prefix) === 0) {
                $handledUri = substr($uri, strlen($this->_prefix)) ?: '/';
            } else {
                $handledUri = false;
            }
        } else {
            $handledUri = $uri;
        }

        $area = null;
        $routes = $this->_simple_routes;
        if ($handledUri === false) {
            $parts = false;
        } elseif (isset($routes[$method][$handledUri])) {
            $parts = $routes[$method][$handledUri]->match($handledUri, $method);
        } elseif (isset($routes[''][$handledUri])) {
            $parts = $routes[''][$handledUri]->match($handledUri, $method);
        } else {
            $parts = false;
            $routes = $this->_regex_routes;
            for ($i = count($routes) - 1; $i >= 0; $i--) {
                $route = $routes[$i];
                if (($parts = $route->match($handledUri, $method)) !== false) {
                    if ($handledUri !== '/' && $this->_areas) {
                        if (($pos = strpos($handledUri, '/', 1)) === false) {
                            $area = Text::camelize(substr($handledUri, 1));
                        } else {
                            $area = Text::camelize(substr($handledUri, 1, $pos - 1));
                        }

                        if (!in_array($area, $this->_areas, true)) {
                            $area = null;
                        }
                    }
                    break;
                }
            }

            if ($parts === false) {
                if ($handledUri !== '/' && $this->_areas) {
                    if (($pos = strpos($handledUri, '/', 1)) !== false) {
                        $area = Text::camelize(substr($handledUri, 1, $pos - 1));
                        if (in_array($area, $this->_areas, true)) {
                            $handledUri = substr($handledUri, $pos);
                        } else {
                            $area = null;
                        }
                    } else {
                        $area = Text::camelize(substr($handledUri, 1));
                        if (in_array($area, $this->_areas, true)) {
                            $handledUri = '/';
                        } else {
                            $area = null;
                        }
                    }
                }

                $handledUri = $handledUri === '/' ? '/' : rtrim($handledUri, '/');
                $parts = $this->_default_route->match($handledUri, $method);
            }
        }

        if ($parts === false) {
            return false;
        }

        $context->matched = true;

        if ($area) {
            $context->area = $area;
        } elseif (isset($parts['area'])) {
            $context->area = $parts['area'];
        }

        $context->controller = $parts['controller'];
        $context->action = $parts['action'];
        $context->params = isset($parts['params']) ? $parts['params'] : [];

        return $context;
    }
810286
public function request($method = 'GET', $uri = '', $options = [])
    {
        try {
            // Make the request.
            return $this->getClient()->request($method, $uri, $this->getRequestOptions($options));
        } catch (ClientException $e) {
            // We are using token auth and probably token expired.
            if ($this->authMethod == 'token' && $e->getCode() == 401 && ! $this->isThrottledReached()) {
                // Try refresh token.
                $this->fetchToken(true);

                // Try requesting again.
                return $this->request($method, $uri, $options);
            }
            // Clear throttle for this request.
            $this->clearThrottle();
            // Call Failed Request.
            $this->failedRequest($e->getResponse());
        }
    }
94729
public function addRoute(array $method, string $uri, $action): Route {
        if (is_string($action)) {
            $action = $this->addPackage($action);
        }
        $uri = $this->addPrefix($uri);
        $route = new Route($uri, is_callable($action) ? $action : function() use ($action) {
            return $this->makeResponse($action);
        }, $method, $this->globalFilters);
        foreach ($route->getMethods() as $item) {
            $this->staticRouteMap[$item][$uri] = $route;
        }
        return $route;
    }
1228065
public function dispatch($object, string $method)
    {
        $reflector = new ReflectionMethod($object, $method);

        $parameters = $this->makeParameters($reflector->getParameters());

        return $reflector->invoke($object, ...$parameters);
    }
317684
protected function _getRouteMethods(Request $r, string $method)
  {
    $method = ucfirst($method);
    if($r->isXmlHttpRequest())
    {
      yield 'ajax' . $method;
      yield 'ajax' . ucfirst(strtolower($r->getMethod())) . $method;
    }

    yield strtolower($r->getMethod()) . $method;
    yield 'process' . $method; //support for all methods
    return null;
  }
1260926
public function dispatch(int $status, string $path, string $method, $route)
    {
        // not found
        if ($status === RouterInterface::NOT_FOUND) {
            return $this->handleNotFound($path, $method);
        }

        // method not allowed
        if ($status === RouterInterface::METHOD_NOT_ALLOWED) {
            return $this->handleNotAllowed($path, $method, $route);
        }

        // trigger route found event
        $this->fire(self::ON_FOUND, [$path, $route]);

        $result = null;
        $options = $route->getOptions();

        // fire enter event
        // schema,domains ... metadata validate
        if (isset($options['enter']) && false === RouteHelper::call($options['enter'], [$options, $path])) {
            return $result;
        }

        $handler = $route->getHandler();
        $args = $route->getParams();

        try {
            // trigger route exec_start event
            $this->fire(self::ON_EXEC_START, [$path, $route]);

            $globChains = $this->getRouter()->getChains();
            $chains = $route->getChains();

            $result = $this->callHandler($path, $method, $handler, $args);

            // fire leave event
            if (isset($options['leave'])) {
                RouteHelper::call($options['leave'], [$options, $path]);
            }

            // trigger route exec_end event
            $this->fire(self::ON_EXEC_END, [$path, $route, $result]);
        } catch (\Throwable $e) {
            // trigger route exec_error event
            if ($cb = $this->getOption(self::ON_EXEC_ERROR)) {
                return RouteHelper::call($cb, [$e, $path, $route]);
            }

            throw $e;
        }

        return $result;
    }