Returns from the specified collection the first route similar to the current url.

@param RouteCollection $routes The route collection.
@param HttpContextBase $httpContext The context of the request.

@return Route|null
334641
private function match($routes, $httpContext) {
        $csm = false ? '' : 'i';
        $path = trim($httpContext->getRequest()->rawUrl(), '/');
        
        if (($qsIndex = strpos($path, '?')) !== false) {
            $path = substr($path, 0, $qsIndex);
        }

        if ($path == 'index.php') {
            $path = '';
        }

        $cache = $httpContext->getCache();
        $cacheKey = '__route_' . $routes->getName() . '_' . $path;

        if ($cache->get($cacheKey) !== null) {
            return $cache->get($cacheKey);
        }

        foreach($routes as $route) {
            $segments = $cache->getOrAdd(
                '__route_segments_0_' . $route->template,
                $route->getSegments(),
                1200
            );

            // make final pattern
            $pattern = '';

            foreach ($segments as $segment) {
                if (!empty($segment->before)) {
                    $pattern .= $segment->before;
                }

                $pattern .= $segment->pattern;

                if (!empty($segment->after)) {
                    $pattern .= $segment->after;
                }

                if (empty($segment->glued)) {
                    if ($segment->optional || !empty($segment->end) || !empty($segment->preEnd)) {
                        $pattern .= '(\/|)';
                    }
                    else {
                        $pattern .= '\/';
                    }
                }
            }

            // test url
            if (preg_match('/^' . $pattern . '$/s' . $csm, $path, $matches) === 1) {
                // match is found
                $result = clone $route;
                $values = array();

                foreach ($segments as $segment) {
                    $name = $segment->name;

                    if (!empty($matches[$name])) {
                        if (empty($values[$name])) {
                            $values[$name] = $matches[$name];
                        }
                    }

                    if (!empty($segment->default)) {
                        if (empty($values[$name]) && $segment->default != UrlParameter::OPTIONAL) {
                            $values[$name] = $segment->default;
                        }
                    }
                }

                if (!empty($route->defaults)) {
                    foreach ($route->defaults as $name => $defaultValue) {
                        if (empty($values[$name]) && $defaultValue != UrlParameter::OPTIONAL) {
                            $values[$name] = $defaultValue;
                        }
                    }
                }

                if (true) {
                    $values = array_map('strtolower', $values);
                }

                $result->values = $values;

                $cache->add($cacheKey, $result, 1200);

                return $result;
            }
        }

        $cache->add($cacheKey, null, 1200);

        return null;
    }
1129506
public static function create(RouteCollection $routes): self
    {
        $factory = new PathPatternFactory();
        $compiler = new MultiPatternCompiler($factory);

        return new self($routes, $compiler);
    }
908289
public function find(Request $request, array $routes)
    {
        foreach ($routes as $route) {

            if(!$this->matchMethod($request, $route)){
                continue;
            }

            if(!$this->matchContentType($request, $route)){
                continue;
            }

            if(!$this->matchFilters($route)){
                continue;
            }

            $routeMatches = $this->matchPattern($request, $route);
            if ($routeMatches) {
                $route->setMatches($routeMatches);
                return $route;
            }
        }
        throw new RouteException(
            sprintf('No route found for uri "%s"', $request->getRequestUri()),
            $request,
            $routes
        );
    }
918687
public function getRouter(RequestContext $requestContext)
    {
        if (!$this->router) {
            if (!$this->getConfigDataProvider()) {
                throw new \LogicException(
                    "Cannot use CacheableRouterProvider because 'routing.config' not configured."
                );
            }
            
            $routerFile = 'routes.yml';
            $routerPath = $this->getConfigDataProvider()->getMandatory('path');
            if (!is_dir($routerPath)) {
                $routerFile = basename($routerPath);
                $routerPath = dirname($routerPath);
            }
            
            $cacheDir                = strcasecmp($this->kernel['routing.config.cache_dir'], "false") == 0 ? null :
                ($this->kernel['routing.config.cache_dir'] ? : $routerPath . "/cache");
            $hash                    = md5(
                realpath($cacheDir) . "/" . realpath($routerPath) . "/" . $routerFile
            );
            $matcherCacheClassname   = "ProjectUrlMatcher_$hash";
            $generatorCacheClassname = "ProjectUrlGenerator_$hash";
            $locator                 = new FileLocator([$routerPath]);
            $this->router            = new CacheableRouter(
                $this->kernel,
                //new YamlFileLoader($locator),
                new InheritableYamlFileLoader($locator),
                $routerFile,
                [
                    'cache_dir'             => $cacheDir,
                    'matcher_cache_class'   => $matcherCacheClassname,
                    'generator_cache_class' => $generatorCacheClassname,
                    'matcher_base_class'    => RedirectableUrlMatcher::class,
                    "debug"                 => $this->kernel['debug'],
                ],
                $requestContext
            );
        }
        
        return $this->router;
    }
414485
public static function route(Http\Request $request)
    {
        $path = $request->REQUEST_URI;
        $key = $request->getMethod().'@'.$path;
        $keyAny = 'ANY@'.$path;

        $matchedRoute = null;
        $matchedScore = 0;

        if (isset(self::$routes[$key])) {
            $matchedRoute = self::$routes[$key];
        } elseif (isset(self::$routes[$keyAny])) {
            $matchedRoute = self::$routes[$keyAny];
        } else {
            foreach (self::$routes as $key2 => $route) {
                if ($route->getMethod() != 'ANY' && $route->getMethod() != $request->getMethod()) {
                    continue;
                }

                $score = $route->getScore($path, $request->getMethod());
                if ($score > $matchedScore) {
                    $matchedRoute = $route;
                    $matchedScore = $score;
                }
            }
        }

        if ($matchedRoute) {
            $matchedRoute->setUrl($path);
        } elseif (self::$_404route) {
            $matchedRoute = self::$_404route;
        } else {
            throw new Exceptions\RouteException('Route not found');
        }
        return $matchedRoute;
    }
374061
public function getRouteByPath($path, RequestContext $context, array &$routeAttributes = [])
    {
        $path = $this->normalizePath($path);
        $potentialRoutes = $this->filterRouteCollectionForPath($this->getRoutes(), $path);
        $matcher = new UrlMatcher($potentialRoutes, $context);
        $routeAttributes = $matcher->match($path);

        return $potentialRoutes->get($routeAttributes['_route']);
    }
861316
protected static function getAssetContentsByRoute($route)
    {
        $result = null;
        try {
            $app = Application::getFacadeApplication();
            $router = $app->make(RouterInterface::class);
            $context = new RequestContext();
            $context->fromRequest($app->make(Request::class));
            $context->setMethod('GET');
            $matched = $router->getRouteByPath($route, $context);
            $controller = $matched->getAction();
            $callable = null;
            if (is_string($controller)) {
                $chunks = explode('::', $controller, 2);
                if (count($chunks) === 2) {
                    if (class_exists($chunks[0])) {
                        $array = [$app->make($chunks[0]), $chunks[1]];
                        if (is_callable($array)) {
                            $callable = $array;
                        }
                    }
                } else {
                    if (class_exists($controller) && method_exists($controller, '__invoke')) {
                        $callable = $app->make($controller);
                    }
                }
            } elseif (is_callable($controller)) {
                $callable = $controller;
            }
            if ($callable !== null) {
                ob_start();
                $r = call_user_func($callable, false);
                if ($r instanceof Response) {
                    $result = $r->getContent();
                } elseif ($r !== false) {
                    $result = ob_get_contents();
                }
                ob_end_clean();
            }
        } catch (Exception $x) {
        }

        return $result;
    }
364338
protected function preFilterRoutes(Request $request, RouteCollectionInterface $routes)
    {
        if ($routes instanceof CachedCollection && $sRoutes = $routes->findByStaticPath($request->getPath())) {
            $routes = 0 !== count($sRoutes->all()) ? $sRoutes : $routes;
        }

        return $routes->findByMethod($request->getMethod());
    }
456331
private function searchRouter($routes) 
    {
        foreach ($routes as $route) {
            if (!preg_match_all('#^' . $route['request'] . '$#', $this->request, $matches, PREG_OFFSET_CAPTURE))
                continue;
            // Rework matches to only contain the matches, not the orig string
            $matches = array_slice($matches, 1);

            // Extract the matched URL parameters (and only the parameters)
            $params = array_map(function ($match, $index) use ($matches) {

                // We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
                if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
                    return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
                } // We have no following parameters: return the whole lot
                else {
                    return (isset($match[0][0]) ? trim($match[0][0], '/') : null);
                }
            }, $matches, array_keys($matches));

            $route['params'] = $params;
            return $route;
        }
        //not exists ...
        return false;
    }
1125791
public function match($httpMethod, $path)
    {
        $path = $this->parsePath($path);

        if (($route = $this->collector->findStaticRoute($httpMethod, $path)) ||
            ($route = $this->matchDynamicRoute($httpMethod, $path))) {
             $route->setMatcher($this);

            return $route;
        }

        $this->matchSimilarRoute($httpMethod, $path);
    }
225447
public function createRouteCollection()
    {
        $routeCollection  = $this->createNew(RouteCollection::class);

        $routeCollection->addRoute('GET', '/{resourceNamePlural}', [$this, 'callGetResources']);
        $routeCollection->addRoute('POST', '/{resourceNamePlural}', [$this, 'callCreateNewResource']);
        $routeCollection->addRoute('PUT', '/{resourceNamePlural}', [$this, 'callCreateNewResource']);
        $routeCollection->addRoute('HEAD', '/{resourceNamePlural}', [$this, 'callMethodNotAllowed']);
        $routeCollection->addRoute('DEL', '/{resourceNamePlural}', [$this, 'callMethodNotAllowed']);

        $routeCollection->addRoute('GET', '/{resourceNamePlural}/{id}', [$this, 'callGetResource']);
        $routeCollection->addRoute('POST', '/{resourceNamePlural}/{id}', [$this, 'callEditResource']);
        $routeCollection->addRoute('PUT', '/{resourceNamePlural}/{id}', [$this, 'callEditResource']);
        $routeCollection->addRoute('HEAD', '/{resourceNamePlural}/{id}', [$this, 'callResourceExists']);
        $routeCollection->addRoute('DEL', '/{resourceNamePlural}/{id}', [$this, 'calldDeleteResource']);

        $routeCollection->addRoute('GET', '/{resourceNamePlural}/{id}/{childNamePlural}', [$this, 'callGetChildResources']);
        $routeCollection->addRoute('POST', '/{resourceNamePlural}/{id}/{childNamePlural}', [$this, 'callCreateNewChildResource']);
        $routeCollection->addRoute('PUT', '/{resourceNamePlural}/{id}/{childNamePlural}', [$this, 'callCreateNewChildResource']);
        $routeCollection->addRoute('HEAD', '/{resourceNamePlural}/{id}/{childNamePlural}', [$this, 'callMethodNotAllowed']);
        $routeCollection->addRoute('DEL', '/{resourceNamePlural}/{id}/{childNamePlural}', [$this, 'callMethodNotAllowed']);

        return $routeCollection;
    }
1262031
public function buildSiteList(ControllerContext $controllerContext)
    {
        $requestUriHost = $controllerContext->getRequest()->getHttpRequest()->getUri()->getHost();

        $domainsFound = false;
        $sites = [];
        foreach ($this->siteRepository->findOnline() as $site) {
            $uri = null;
            $active = false;
            /** @var $site Site */
            if ($site->hasActiveDomains()) {
                $activeHostPatterns = $site->getActiveDomains()->map(function ($domain) {
                    return $domain->getHostname();
                })->toArray();
                $active = in_array($requestUriHost, $activeHostPatterns, true);
                if ($active) {
                    $uri = $controllerContext->getUriBuilder()
                        ->reset()
                        ->setCreateAbsoluteUri(true)
                        ->uriFor('index', [], 'Backend\Backend', 'Neos.Neos');
                } else {
                    $uri = $controllerContext->getUriBuilder()
                        ->reset()
                        ->uriFor('switchSite', ['site' => $site], 'Backend\Backend', 'Neos.Neos');
                }
                $domainsFound = true;
            }

            $sites[] = [
                'name' => $site->getName(),
                'nodeName' => $site->getNodeName(),
                'uri' => $uri,
                'active' => $active
            ];
        }

        if ($domainsFound === false) {
            $uri = $controllerContext->getUriBuilder()
                ->reset()
                ->setCreateAbsoluteUri(true)
                ->uriFor('index', [], 'Backend\Backend', 'Neos.Neos');
            $sites[0]['uri'] = $uri;
        }

        return $sites;
    }
796710
protected function populateRoutes(RouteCollection $routes)
    {
        $factory = $this->app->make(RouteHandlerFactory::class);

        $callback = include __DIR__.'/routes.php';
        $callback($routes, $factory);

        $this->app->make('events')->fire(
            new ConfigureApiRoutes($routes, $factory)
        );
    }
1222044
public function match(Request $request)
	{
		foreach ($this->routes->filterByMethod($request->getMethod()) as $route)
		{
			if ($route->isMatch($request->getPathInfo()))
			{
				return $route;
			}
		}

		return null;
	}
1371795
public function searchRouteAction( $context )
    {
        /** @var SearchAdapter $searchAdapter */
        $searchAdapter = $this->get('netgen_search_and_filter.route_'.$context);

        /** @var Form $form */
        $form = $searchAdapter->getForm();

        $response = new Response();

        $pager = new Pagerfanta( $searchAdapter );
        $pager->setMaxPerPage( $searchAdapter->getPageLimit() );

        $showResults = $this->getPage( $pager, $form );

        $request = $this->container->get('request');

        return $this->render($searchAdapter->getResultTemplate(), array(
            'pagelayout' => $this->container->getParameter("netgen_search_and_filter.main_pagelayout"),
            'route' => $request->get('_route'),
            'context' => $context,
            'form_template' => $searchAdapter->getFormTemplate(),
            'form' => $form->createView(),
            'pager' => $pager,
            'show_results' => $showResults,
            'query_string' => array($form->getName() => $form->getData()),
            'current_locale' => $this->getConfigResolver()->getParameter('RegionalSettings.Locale')
        ), $response);
    }
1219129
public function create(RouteCollection $routes): Tree
    {
        $routesArray = $routes->all();

        $routesPaths = array_map(function (Route $route) {
            return $this->serializer->serialize($route->getPath());
        }, $routesArray);

        $tree = new Tree();

        /** @var RoutePath[] $pathArray */
        foreach ($routesPaths as $index => $pathArray) {
            $route = $routesArray[$index];

            /** @var TreeNode $treeNode */
            $treeNode = $tree;

            foreach ($pathArray as $path) {
                $treeNode = $this->addPathPartToTree($treeNode, $path, $route, $index);
            }
        }

        return $tree;
    }
464894
private function findRoute(array $pathSegments = null) {

	    if(!count($this->routes)) {
	        throw new ApplicationException('Routing aborted: No routes defined.');
        }

		// if no page given try to get the first from list

		if(empty($pathSegments)) {

			return reset($this->routes);
		}

		$pathToCheck	= implode('/', $pathSegments);
		$requestMethod	= Request::createFromGlobals()->getMethod();

		/* @var Route $foundRoute */

		$foundRoute = null;

        /* @var Route $default */

		$default = null;

		// iterate over routes and try to find the "best" match

        /* @var Route $route */

		foreach($this->routes as $route) {

			// keep default route as fallback, when no match is found

			if($route->getRouteId() === 'default') {
				$default = $route;
			}

			// pick route only when request method requirement is met

			if(
				preg_match('~^' . $route->getMatchExpression() . '$~', $pathToCheck) &&
				$route->allowsRequestMethod($requestMethod)
			) {

				// if no route was found yet, pick this first match

				if(!isset($foundRoute)) {
                    $foundRoute = $route;
                    continue;
                }

                // prefer route which is more specific with request methods

                if(count($route->getRequestMethods()) > count($foundRoute->getRequestMethods())) {
                    continue;
                }

                // a route with less (or no) placeholders is preferred over one with placeholders

                if(count($route->getPlaceholderNames()) > count($foundRoute->getPlaceholderNames())) {
                    continue;
                }

                // if a route has been found previously, choose the more "precise" and/or later one
                // choose the route with more satisfied placeholders
                // @todo could be optimized

                $foundRouteSatisfiedPlaceholderCount = count($this->getSatisfiedPlaceholders($foundRoute, $pathToCheck));
                $routeSatisfiedPlaceholderCount = count($this->getSatisfiedPlaceholders($route, $pathToCheck));

                if (
                    ($routeSatisfiedPlaceholderCount - count($route->getPlaceholderNames())) < ($foundRouteSatisfiedPlaceholderCount - count($foundRoute->getPlaceholderNames()))
                ) {
                    continue;
                }
                if (
                    ($routeSatisfiedPlaceholderCount - count($route->getPlaceholderNames())) === ($foundRouteSatisfiedPlaceholderCount - count($foundRoute->getPlaceholderNames())) &&
                    count($route->getPlaceholderNames()) > count($foundRoute->getPlaceholderNames())
                ) {
                    continue;
                }

                $foundRoute = $route;

			}
		}

		// return "normal" route, if found

		if(isset($foundRoute)) {
			return $foundRoute;
		}

		// return default route as fallback (if available)

		return $default;
	}