Perform the route dispatching. Check static routes first followed by variable routes.

@param $httpMethod
@param $uri
@throws HttpRouteNotFoundException
972176
protected function dispatchRoute($httpMethod, $uri)
    {
        if (isset($this->staticRouteMap[$uri])) {
            return $this->dispatchStaticRoute($httpMethod, $uri);
        }

        return $this->dispatchVariableRoute($httpMethod, $uri);
    }
1211413
public function route(array $method, $uri, $callback, $options = [])
    {
        if (is_array($uri)) {
            foreach ($uri as $u) {
                $this->route($method, $u, $callback, $options);

            }
            return $this;
        }
        $options = array_merge(['ajaxOnly' => false, 'continue' => false], (array)$options);

        if ($uri != '/') {
            $uri = $this->removeDuplSlash($uri) . '/';
        }
        // Replace named uri param to regex pattern.
        $pattern = $this->namedParameters($uri);
        $this->currentUri = $pattern;

        if ($options['ajaxOnly'] == false || $options['ajaxOnly'] && $this->req->ajax) {
            // If matched before, skip this.
            if ($this->matched === false) {
                // Prepare.
                $pattern = $this->prepare(
                    str_replace(['/?', '/*'], [$this->pattern['/?'], $this->pattern['/*']], $this->removeDuplSlash($this->group . $pattern))
                );

                // If matched.
                $method = count($method) > 0 ? in_array($this->req->method, $method) : true;
                if ($method && $this->matched($pattern)) {
                    if ($this->isGroup) {
                        $this->prams = array_merge($this->pramsGroup, $this->prams);
                    }

                    $this->req->args = $this->bindArgs($this->prams, $this->matchedArgs);

                    $this->matchedPath = $this->currentUri;
                    $this->routeCallback[] = $callback;

                    if ($options['continue']) {
                        $this->matched = false;
                    }
                }
            }
        }
        $this->_as($this->removeParameters($this->trimSlash($uri)));
        return $this;
    }
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());
        }
    }
432519
public function isCachable(string $url, string $httpMethod) : bool
    {
        return $httpMethod === ClientInterface::HTTP_GET && $this->getCache() !== null;
    }
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;
    }
762236
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
		switch (httpMethod) {
		case GET:
			return new HttpGetHC4(uri);
		case DELETE:
			return new HttpDeleteHC4(uri);
		case HEAD:
			return new HttpHeadHC4(uri);
		case OPTIONS:
			return new HttpOptionsHC4(uri);
		case POST:
			return new HttpPostHC4(uri);
		case PUT:
			return new HttpPutHC4(uri);
		case TRACE:
			return new HttpTraceHC4(uri);
		case PATCH:
			return new HttpPatch(uri);
		default:
			throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
		}
	}
962139
public function validate(string $requestUri, string $requestMethod): bool
    {
        $route = $this->findRoute($this->filterUri($requestUri), $requestMethod);

        if ($route instanceof Route) {
            $this->buildValidRoute($route);
            return true;
        }

        $this->buildErrorRoute();

        return false;
    }
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;
    }
95804
public void add(HttpMethod httpMethod, RouteImpl route) {
        add(httpMethod, route.getPath() , route.getAcceptType(), route);
    }
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' => []
		];
	}
1134480
protected function createRoute( $methods, $uri, $action )
	{
		// If the route is routing to a controller we will parse the route action into
		// an acceptable array format before registering it and creating this route
		// instance itself. We need to build the Closure that will call this out.
		if ( $this->actionReferencesController( $action ) )
			$action = $this->convertToControllerAction( $action );

		$route = $this->newRoute( $methods, $this->prefix( $uri ), $action );

		// If we have groups that need to be merged, we will merge them now after this
		// route has already been created and is ready to go. After we're done with
		// the merge we will be ready to return the route back out to the caller.
		if ( $this->hasGroupStack() )
			$this->mergeGroupAttributesIntoRoute( $route );

		$this->addWhereClausesToRoute( $route );

		return $route;
	}
459118
public function dispatch(string $httpMethod, string $uri) : array
    {
        $urlPath = rawurldecode(parse_url($uri, PHP_URL_PATH));
        $routeInfo = $this->routeDispatcher->dispatch($httpMethod, $urlPath);
        return $routeInfo;
    }
1049627
public function dispatch($requestUrl = null, $requestMethod = null) 
	{
		$params = array();
		$match = false;
		// set Request Url if it isn't passed as parameter
		if ($requestUrl === null) {
			$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
		}
		// strip base path from request url
		$requestUrl = substr($requestUrl, strlen($this->basePath));
		// Strip query string (?a=b) from Request Url
		if (($strpos = strpos($requestUrl, '?')) !== false) {
			$requestUrl = substr($requestUrl, 0, $strpos);
		}
		// Strip anchors from the url
		// if (($strpos = strpos($requestUrl, '#')) !== false) {
		// 	$requestUrl = substr($requestUrl, 0, $strpos);
		// }
		// set Request Method if it isn't passed as a parameter
		if ($requestMethod === null) {
			$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
		}
		foreach ($this->routes as $handler) {
			list($method, $_route, $target, $name) = $handler;
			$methods = explode('|', $method);
			$method_match = false;
			// Check if request method matches. If not, abandon early. (CHEAP)
			foreach ($methods as $method) {
				if (strcasecmp($requestMethod, $method) === 0) {
					$method_match = true;
					break;
				}
			}
			// Method did not match, continue to next route.
			if (!$method_match) {
				continue;
			}
			// Check for a wildcard (matches all)
			if ($_route === '*') {
				$match = true;
			} elseif (isset($_route[0]) && $_route[0] === '@') {
				$pattern = '`' . substr($_route, 1) . '`u';
				$match = preg_match($pattern, $requestUrl, $params);
			} else {
				$route = null;
				$regex = false;
				$j = 0;
				$n = isset($_route[0]) ? $_route[0] : null;
				$i = 0;
				// Find the longest non-regex substring and match it against the URI
				while (true) {
					if (!isset($_route[$i])) {
						break;
					} elseif (false === $regex) {
						$c = $n;
						$regex = $c === '[' || $c === '(' || $c === '.';
						if (false === $regex && false !== isset($_route[$i+1])) {
							$n = $_route[$i + 1];
							$regex = $n === '?' || $n === '+' || $n === '*' || $n === '{';
						}
						if (false === $regex && $c !== '/' && (!isset($requestUrl[$j]) || $c !== $requestUrl[$j])) {
							continue 2;
						}
						$j++;
					}
					$route .= $_route[$i++];
				}
				$regex = $this->compileRoute($route);
				$match = preg_match($regex, $requestUrl, $params);
			}
			if (($match == true || $match > 0)) {
				if ($params) {
					foreach ($params as $key => $value) {
						if (is_numeric($key)) unset($params[$key]);
					}
				}			
				$mm = array(
					'target' => $target,
					'params' => $params,
					'name' => $name
				);
				if ($match) {	
				  //we are going to change this to use all be in the router function
				  //break up the target at the @ symbol. first part is function second is the file 
				  $target = explode('@', $mm['target']);
				  $method = $target[0];
				  $class = "\\App\\Controllers\\".$target[1];
				  //include the source file
				  include $this->controllersDir . str_replace('\\', '/', $target[1]) . '.php';
				  //instantiate the class
				  $instance = new $class();
				  //this is where we will place our middleware. first check to see if the there is an alias in 
				  //the middleware array and then execute it against our controller.
				  //get the middleware array from the instance
				  $instanceMiddleware = $instance->getMiddleware();
				  $middleware = $this->getMiddleWareArray();
					//count the instance middleware array
					$middlewareCnt = count($instanceMiddleware);
				  $middlewareInstances = [];
				  //build an acceptible middleware list to send to relay
				  $i = 0;
				  foreach($instanceMiddleware as $val) {
				  	//then loop through the middleware and see if we have a match
					  foreach ($middleware as $key => $value) {
							if($val==$key) {
						  	//check if its an array if it is we have to add them to the container individually.
						  	$middlewareInstances[$i][]=$instanceMiddleware[$i];
						  	if (is_array($value)) {
						  		//first index is the middleware class and the second index is the plugin
						  		for($j=0;$j<count($value);$j++) {
						  			$middlewareInstances[$i][] = $value[$j];
					  				$i++;
						  		}
						  	} else {
						  		//just a middleware class. This class will extend from another and doesnt need the plugin portion
					  			$middlewareInstances[$i][] = $value;
					  			$i++;
						  	}
						  }
					  }
				  }
				  //get the request array
				if (defined('PHPUNIT_BETASYNTAX_TESTSUITE') == true) { 
					$requestMethod = $requestMethod;
				}
				// } else {
				// 	if($requestMethod === null) {
			 //  			$requestMethod = $_SERVER['REQUEST_METHOD'];	
				// 	} else {
				// 		$requestMethod = $_SERVER['REQUEST_METHOD'];
				// 	}
				// }
			  	//instantiate our request and response for Relay
			  	$request = new Request($requestMethod,$requestUrl);
			  	$response = new Response;
			  	$queue = [];
			  	//build the middleware queue
			  	for($i=0;$i<count($middlewareInstances);$i++) {
			  			$queue[] = $middlewareInstances[$i][1];
			  	}
			  	//setup the automatic resolver
					$resolver = function ($class) {
					    return new $class();
					};
					//build the Relay builder class
					$relayBuilder = new RelayBuilder($resolver);
					$relay = $relayBuilder->newInstance($queue);
					//run the middleware against our controller
					$response = $relay($request, $response);
					//finally if all our middleware passed on the response we can then run our intended controller action				
					if (!defined('PHPUNIT_BETASYNTAX_TESTSUITE') == true) { 
						$instance->$method($mm['params']);
					} 
					$this->routeFound=true;
				}
			}
		}
		if(!$this->routeFound) {
			if (defined('PHPUNIT_BETASYNTAX_TESTSUITE') == true) { 
				return true;
			} else {
				view('Errors/404.haml'); 	
			}
		} else {
			return false;
		}
	}
1136337
protected function createRoute($methods, $uri, $action)
    {
        if (is_callable($action)) {
            $action = array('uses' => $action);
        }

        // If the route is routing to a controller we will parse the route action into
        // an acceptable array format before registering it and creating this route
        // instance itself. We need to build the Closure that will call this out.
        else if ($this->actionReferencesController($action)) {
            $action = $this->convertToControllerAction($action);
        }

        // If no "uses" property has been set, we will dig through the array to find a
        // Closure instance within this list. We will set the first Closure we come
        // across into the "uses" property that will get fired off by this route.
        else if (! isset($action['uses'])) {
            $action['uses'] = $this->findActionClosure($action);
        }

        if (isset($action['middleware']) && is_string($action['middleware'])) {
            $action['middleware'] = explode('|', $action['middleware']);
        }

        $route = $this->newRoute(
            $methods, $uri = $this->prefix($uri), $action
        );

        // If we have groups that need to be merged, we will merge them now after this
        // route has already been created and is ready to go. After we're done with
        // the merge we will be ready to return the route back out to the caller.
        if (! empty($this->groupStack)) {
            $this->mergeGroupAttributesIntoRoute($route);
        }

        $this->addWhereClausesToRoute($route);

        return $route;
    }
314386
protected function createRoute($methods, $uri, $action)
    {
        $route = parent::createRoute($methods, $uri, $action);
        if (! empty($this->groupStack)) {
            $route = $this->mergePriority($route);
        }

        return $route;
    }
1245053
protected function newRoute($methods, $uri, $action)
	{
		$route = new Route($methods, $uri, $action);
		$priority = Router::MEDIUM - $this->routes->count();
		$route->setPriority($priority);
		return $route;
	}
868958
public function register($route, $callback, $httpMethod = '')
    {
        // Convert empty routes to the string 'method:home'
        if (!$route) 
            $route = 'home';
        
        // append the http method supplied
        if ($httpMethod) 
            $route = strtolower($httpMethod).':'.$route;
                
        $this->routes[$route] = $callback;
    }