Evaluate request uri.

@param string $requestUri
@param string $requestMethod

@return bool
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;
    }
290465
private static function fixRequestUri(string $requestUri): string
    {
        return preg_replace_callback('|[^a-zA-Z0-9-._~:/?[\\]@!$&\'()*+,;=%]|', function (array $matches) {
            return '%' . sprintf('%02X', ord($matches[0]));
        }, $requestUri);
    }
20198
protected function matchRequestUriWithMap($request_uri, $url_from_map)
    {
        $url_from_map = preg_quote($url_from_map);
        $request_uri = urldecode($request_uri);

        // Don't know what's that for: "/$something..." => "/$something"
        $regex = preg_replace('/\\\\\$([\w\d]+)\.\.\./', '(?P<$1>.+)', str_replace('\.\.\.', '...', $url_from_map));

        // Find named parameters in URL /$something => $matches['something'] = $something
        $regex = preg_replace('/\\\\\$([\w\d]+)/', '(?P<$1>[^\/]+)', $regex);

        if (preg_match(":^$regex$:", $request_uri, $matches)) {
            return $matches;
        } else {
            return array();
        }
    }
252730
public boolean shouldNotCache(String requestUri) {
		String uri = requestUri.toLowerCase();
		return checkContains(uri, noCacheIdentifiers) || checkSuffixes(uri, noCacheSuffixes);
	}
285627
public function handle( $requestUri )
    {
        $url = $this->_di->getService( "url" );

        /**
         * Remove the uri prefix from the request uri
         * (the uri prefix is added when route is created)
         */
        $requestUri = str_replace( $url->getUriPrefix(), "", $requestUri );

        $request_route = $this->_createRoute( ["uri" => $requestUri] );

        /**
         * Passing the uri to the get function in the url service to make sure the uri:s have a consistent format
         */
        //$request_route->setUri( $url->get( $request_route->getUri() ) );

        $request_route_uri_fragments = explode( "/", $request_route->getUri() );

        foreach ($this->_routeDefinitions as $routeDefinition)
        {
            $route = call_user_func($routeDefinition);

            /**
             * Passing the uri to the get function in the url service to make sure the uri:s have a consistent format
             */
            //$route->setUri( $url->get( $route->getUri() ) );

            $route_uri_fragments = explode( "/", $route->getUri() );

            /**
             * Check if request uri and route uri has the same number of fragments.
             * If not, continue to next route.
             */
            if ( count($route_uri_fragments) != count($request_route_uri_fragments) )
            {
                continue;
            }

            $params = array();

            /**
             * Compare every fragment of the uris
             */
            for ( $i = 0; $i < count($route_uri_fragments); $i++ )
            {
                /**
                 * Parameters are not compared
                 */
                if ( $route_uri_fragments[$i] == "{param}" )
                {
                    $params[] = $request_route_uri_fragments[$i];

                    continue;
                }

                /**
                 * If a fragment is not equal -> continue to next route
                 */
                if ( $route_uri_fragments[$i] != $request_route_uri_fragments[$i] )
                {
                    continue 2;
                }
            }

            $route->setParams( $params );

            /**
             * We have a match!
             */
            $this->_matchRoute = $route;

            return;
        }

        /**
         * No match :(
         * If not found route has been set -> set as out match route
         */
        if ( isset($this->_notFoundRoute) )
        {
            $this->_matchRoute = $this->_notFoundRoute;

            return;
        }

        /**
         * With no other options, we set the match route to a default route
         */
        $this->_matchRoute = new Route();
    }
628143
public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) {
        this.requestURI = requestURI;
        if (containsHost) {
            this.state |= FLAG_URI_CONTAINS_HOST;
        } else {
            this.state &= ~FLAG_URI_CONTAINS_HOST;
        }
        return this;
    }
1007029
public function resolve($uri, $baseUri = null)
    {
        $components = $this->parse($uri);
        $path = $components['path'];

        if ((array_key_exists('scheme', $components)) && ('http' === $components['scheme'])) {
            return $uri;
        }

        $baseComponents = $this->parse($baseUri);
        $basePath = $baseComponents['path'];

        $baseComponents['path'] = UriResolver::combineRelativePathWithBasePath($path, $basePath);

        return $this->generate($baseComponents);
    }
1373555
public function match($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);
		}

		// 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($methods, $route, $target, $name) = $handler;

			$method_match = (stripos($methods, $requestMethod) !== false);

			// Method did not match, continue to next route.
			if (!$method_match) continue;

			if ($route === '*') {
				// * wildcard (matches all)
				$match = true;
			} elseif (isset($route[0]) && $route[0] === '@') {
				// @ regex delimiter
				$pattern = '`' . substr($route, 1) . '`u';
				$match = preg_match($pattern, $requestUrl, $params) === 1;
			} elseif (($position = strpos($route, '[')) === false) {
				// No params in url, do string comparison
				$match = strcmp($requestUrl, $route) === 0;
			} else {
				// Compare longest non-param string with url
				if (strncmp($requestUrl, $route, $position) !== 0) {
					continue;
				}
				$regex = $this->compileRoute($route);
				$match = preg_match($regex, $requestUrl, $params) === 1;
			}

			if ($match) {

				if ($params) {
					foreach($params as $key => $value) {
						if(is_numeric($key)) unset($params[$key]);
					}
				}

				return array(
					'target' => $target,
					'params' => $params,
					'name' => $name
				);
			}
		}
		return false;
	}
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;
		}
	}
1331903
public static MatchResult doMatch(final String requestURI, final String httpMethod) {
        MatchResult ret;
        final int segs = StringUtils.countMatches(requestURI, "/");
        ContextHandlerMeta contextHandlerMeta;
        String concreteKey = httpMethod + "." + requestURI;
        switch (segs) {
            case 1:
                contextHandlerMeta = ONE_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, ONE_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, ONE_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, ONE_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, ONE_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, ONE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
            case 2:
                contextHandlerMeta = TWO_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, TWO_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, TWO_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, TWO_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, TWO_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, TWO_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
            case 3:
                contextHandlerMeta = THREE_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, THREE_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, THREE_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, THREE_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, THREE_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, THREE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
            default:
                contextHandlerMeta = FOUR_MORE_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
        }
    }
561961
protected function detectBaseUri()
    {
        $baseUri = clone $this->uri;
        $baseUri = $baseUri->withQuery('')->withFragment('')->withPath(RequestInformationHelper::getScriptRequestPath($this));

        return $baseUri;
    }
834903
public function dispatchCandidateRoutes($requestUri) {
        $expUri = explode('/',$requestUri);
        $similaridades = [];

        if (count($this->candidateRoutes) > 1) {
            foreach ($this->candidateRoutes as $n => $rota) {
                $padrao = $rota->getPattern();
                if (preg_match('/\[:options\]/', $padrao)) {
                    unset($this->candidateRoutes[$n]);
                }
            }
        }

        foreach ($this->candidateRoutes as $n => $rota) {
            $padrao = $rota->getPattern();
            if (preg_match('/\[:options\]/', $padrao)) {
                $this->matchedRoute = $rota;
                $this->candidateRoutes = [];
                return;
            }

            $naoVariaveis = $this->getNonVariables($padrao);

            foreach ($naoVariaveis as $i => $valor) {
                if(!isset($similaridades[$n]))
                    $similaridades[$n] = 0;

                if (isset($expUri[$i]) && $expUri[$i] == $valor) {
                    $similaridades[$n] += 1;
                }
            }
        }

        $bigger = max(array_values($similaridades));
        $mostSimilar = array_search($bigger, $similaridades);
        $this->matchedRoute = $this->candidateRoutes[$mostSimilar];
        $this->candidateRoutes = [];
    }
431400
protected function loadSystemUris($requestUri = null)
	{
		// Set the request URI.
		// @codeCoverageIgnoreStart
		if (!empty($requestUri))
		{
			$this->set('uri.request', $requestUri);
		}
		else
		{
			$this->set('uri.request', $this->detectRequestUri());
		}

		// @codeCoverageIgnoreEnd

		// Check to see if an explicit base URI has been set.
		$siteUri = trim($this->get('site_uri'));

		if ($siteUri != '')
		{
			$uri = new Uri($siteUri);
		}
		else
		// No explicit base URI was set so we need to detect it.
		{
			// Start with the requested URI.
			$uri = new Uri($this->get('uri.request'));

			// If we are working from a CGI SAPI with the 'cgi.fix_pathinfo' directive disabled we use PHP_SELF.
			if (strpos(php_sapi_name(), 'cgi') !== false && !ini_get('cgi.fix_pathinfo') && !empty($_SERVER['REQUEST_URI']))
			{
				// We aren't expecting PATH_INFO within PHP_SELF so this should work.
				$uri->setPath(rtrim(dirname($_SERVER['PHP_SELF']), '/\\'));
			}
			else
			// Pretty much everything else should be handled with SCRIPT_NAME.
			{
				$uri->setPath(rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\'));
			}

			// Clear the unused parts of the requested URI.
			$uri->setQuery(null);
			$uri->setFragment(null);
		}

		// Get the host and path from the URI.
		$host = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
		$path = rtrim($uri->toString(array('path')), '/\\');

		// Check if the path includes "index.php".
		if (strpos($path, 'index.php') !== false)
		{
			// Remove the index.php portion of the path.
			$path = substr_replace($path, '', strpos($path, 'index.php'), 9);
			$path = rtrim($path, '/\\');
		}

		// Set the base URI both as just a path and as the full URI.
		$this->set('uri.base.full', $host . $path . '/');
		$this->set('uri.base.host', $host);
		$this->set('uri.base.path', $path . '/');

		// Set the extended (non-base) part of the request URI as the route.
		$this->set('uri.route', substr_replace($this->get('uri.request'), '', 0, strlen($this->get('uri.base.full'))));

		// Get an explicitly set media URI is present.
		$mediaURI = trim($this->get('media_uri'));

		if ($mediaURI)
		{
			if (strpos($mediaURI, '://') !== false)
			{
				$this->set('uri.media.full', $mediaURI);
				$this->set('uri.media.path', $mediaURI);
			}
			else
			{
				// Normalise slashes.
				$mediaURI = trim($mediaURI, '/\\');
				$mediaURI = !empty($mediaURI) ? '/' . $mediaURI . '/' : '/';
				$this->set('uri.media.full', $this->get('uri.base.host') . $mediaURI);
				$this->set('uri.media.path', $mediaURI);
			}
		}
		else
		// No explicit media URI was set, build it dynamically from the base uri.
		{
			$this->set('uri.media.full', $this->get('uri.base.full') . 'media/');
			$this->set('uri.media.path', $this->get('uri.base.path') . 'media/');
		}
	}
161335
function makeUri($uri) {
      $a = parse_url($uri);

      if ( (isset($a['scheme'])) && (isset($a['host'])) ) {
        $this->url = $a;
      } else {
        unset($this->url['query']);
        unset($this->url['fragment']);
        $this->url = array_merge($this->url, $a);
      }

      if ($this->useProxy) {
        $requesturi = 'http://' . $this->url['host'] . (empty($this->url['port']) ? '' : ':' . $this->url['port']) . $this->url['path'] . (empty($this->url['query']) ? '' : '?' . $this->url['query']);
      } else {
        $requesturi = $this->url['path'] . (empty($this->url['query']) ? '' : '?' . $this->url['query']);
      }

      return $requesturi;
    }
287111
private function parseRequestUri(): void
    {
        $requestUri = $this->baseClass->getRequestUri();
        $path = \explode('/', $requestUri);
        $pathCnt = \count($path);
        if ($pathCnt > 0) {
            $file = \array_pop($path);
            $path = \sprintf('%%DOCUMENT_ROOT%%%s%s', \implode(DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR);
            $path = $this->baseClass->parsePath($path);

            $file = \explode('.', $file);
            $ext = '';

            if (\count($file) > 1) {
                $ext = \array_pop($file);
            }

            $file = \explode('__', \implode('.', $file));
            $resizeParams = [];

            if (\count($file) > 1) {
                $resizeParams = $this->parseResizeParams(\explode('_', $file[1]));
            }

            $file = $file[0];

            $this->uriParams['path'] = $path;
            $this->uriParams['file'] = $file;
            $this->uriParams['extension'] = $ext;
            $this->uriParams['resize-params'] = $resizeParams;
        }
    }
408511
public function setRequestUri(string $requestUri) : Request
    {
        $pos = strpos($requestUri, '?');

        if ($pos === false) {
            $this->path = $requestUri;
            $this->queryString = '';
            $this->query = [];
        } else {
            $this->path        = substr($requestUri, 0, $pos);
            $this->queryString = substr($requestUri, $pos + 1);

            if ($this->queryString === '') {
                $this->query = [];
            } else {
                parse_str($this->queryString, $this->query);
            }
        }

        $this->requestUri = $requestUri;

        return $this;
    }
4149
@Override
    public URI getURI() throws IOException {
        URL url = getURL();
        try {
            return ResourceUtils.toURI(url);
        } catch (URISyntaxException ex) {
            throw new RuntimeException("Invalid URI [" + url + "]", ex);
        }
    }