Reverse route a named route

@param $routeName
@param array $params Optional array of parameters to use in URL

@throws Exception

@return string The url to the route
552246
public function generate($routeName, array $params = array())
    {
        // Check if route exists
        if (!isset($this->namedRoutes[$routeName])) {
            throw new Exception("No route with the name $routeName has been found.");
        }

        /** @var \PHPRouter\Route $route */
        $route = $this->namedRoutes[$routeName];
        $url = $route->getUrl();

        // replace route url with given parameters
        if ($params && preg_match_all('/:(\w+)/', $url, $param_keys)) {
            // grab array with matches
            $param_keys = $param_keys[1];

            // loop trough parameter names, store matching value in $params array
            foreach ($param_keys as $key) {
                if (isset($params[$key])) {
                    $url = preg_replace('/:'.preg_quote($key,'/').'/', $params[$key], $url, 1);
                }
            }
        }

        return $url;
    }
1081212
public function route($param = null, $default = null)
    {
        $route = \call_user_func($this->getRouteResolver());

        if (\is_null($route) || \is_null($param)) {
            return $route;
        }

        return Arr::get($route[2], $param, $default);
    }
304833
public function getPageBlocksByRouteName($routeName)
    {
        $pageName = $this->routeConfig->getPageName($routeName);

        if (!isset($this->pageBlocks[$pageName])) {
            throw new \Exception(
                sprintf(
                    'Not found blocs for page with name \'%s\' and route name \'%s\'',
                    $pageName,
                    $routeName
                )
            );
        }

        return $this->pageBlocks[$pageName];
    }
2308
public static function map(
		string $url = null, string $destination, string $route_name = null, string $method = null
	) :Route {
		// We cannot allow duplicate route names for reversing reasons
		if($route_name && self::hasRoute($route_name)) {
			// throw an exception
			throw new Exception("Router::map() The route {$route_name} has already been declared");
		}
		// create a new route
		$route = new Route($route_name);
		// configure the route
		$route
			->setUrl($url)
			->setDestination($destination)
			->setMethod($method);
		// add it to the list of known routes
		self::$_routes[$route->name] = $route;
		// return the route for finer tuning
		return self::$_routes[$route->name];
	}
690475
protected function redirectToRefererOrRoute(
        string $routeName,
        array $routeParameters = []
    ): RedirectResponse {
        try {
            return $this->redirectToReferer();
        } catch (CannotRedirectToEmptyRefererUrlException $exception) {
            return $this->redirectToRoute($routeName, $routeParameters);
        }
    }
745621
public function assemble($routeName, array $params = [], array $options = [])
    {
        $nameParts  = explode('/', $routeName, 2);
        $parentName = $nameParts[0];
        $childName  = isset($nameParts[1]) ? $nameParts[1] : null;

        $assemblyResult = $this->routeCollection->get($parentName)->assemble($params, $childName);
        $assemblyResult->path = $this->baseUri['path'] . $assemblyResult->path;

        if (isset($options['query'])) {
            $assemblyResult->query = $options['query'];
        }

        if (isset($options['fragment'])) {
            $assemblyResult->fragment = $options['fragment'];
        }

        return $assemblyResult->generateUri(
            $this->baseUri['scheme'],
            $this->baseUri['host'],
            $this->baseUri['port'],
            (isset($options['enforce_absolute_uri']) && $options['enforce_absolute_uri'])
        );
    }
144189
public function url($route, $params)
    {
        // use array filter to remove keys with null values
        $params += array_filter($this->getEmbedParams());

        return $this->router->generate($route, $params);
    }
1374592
public function pathFor($routeName, $params = array())
    {
        if ($rota = $this->getRoute($routeName)) {
            $pattern = $rota->getPattern();
            $qtdParams = count($rota->getParamNames());

            $withOptions =  preg_match('/\[:options\]/', $pattern);

            if ($qtdParams > 0 && count($params) == 0) {
                throw new \RuntimeException('A rota '.$routeName.' requer '.$qtdParams.' parametro(s)!');
            }

            if ($withOptions && count($params) > 0) {
                $pattern = str_replace('[:options]', '', $pattern);
                $pattern .= implode('/', $params);
            } elseif (count($params) > 0) {
                foreach ($params as $key => $value) {
                    $pattern = str_replace(':'.$key, $value, $pattern);
                }
            }
            return $this->request->getRoot().$pattern;
        }
    }
545481
public function seeCurrentRouteIs($routeName, array $params = [])
    {
        $router = $this->grabService('router');
        if (!$router->getRouteCollection()->get($routeName)) {
            $this->fail(sprintf('Route with name "%s" does not exists.', $routeName));
        }

        $uri = explode('?', $this->grabFromCurrentUrl())[0];
        try {
            $match = $router->match($uri);
        } catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
            $this->fail(sprintf('The "%s" url does not match with any route', $uri));
        }
        $expected = array_merge(['_route' => $routeName], $params);
        $intersection = array_intersect_assoc($expected, $match);

        $this->assertEquals($expected, $intersection);
    }
136802
private function getRoute(string $routeName): Route
    {
        foreach ($this->router->getRouteCollection() as $name => $route) {
            if ($routeName === $name) {
                return $route;
            }
        }

        throw new RuntimeException(sprintf('The route "%s" does not exist.', $routeName));
    }
673712
public function reverseRoute( $controllerName, $actionName )
    {
        // Create a temp route because formatting
        $tempRoute = new Route( ["controllerName" => $controllerName, "actionName" => $actionName] );

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

            if ( $tempRoute->getControllerName() == $route->getControllerName() && $tempRoute->getActionName() == $route->getActionName() )
            {
                return $route->getUri();
            }
        }
    }
638147
public static function route($route, array $params = array())
    {
        list($controller, $action) = Route::routeToAction($route);
        $controller = substr($controller, 0, strlen($controller) - strlen('Controller'));
        $action = substr($action, 0, strlen($action) - strlen('Action'));

        $path = "/" . str_ireplace('\\', '/', $controller) . '/' . $action;
        $query = http_build_query($params);

        $url = $path . (empty($query) ? '' : ('?' . $query));

        return $url;
    }
1047167
public static function linkRoute($name, $params = array(), $url = null)
    {
        //starting defining url and qs
        $url = ($url != '') ? $url : $_SERVER["REQUEST_URI"];
        $url_arr = explode('?', $url);
        $url = $url_arr[0];
        $qs = (isset($url_arr[1])) ? $url_arr[1] : '';
        if (!is_array($params)) $params = (array) $params;
        
        //is a stric-uri?
        if (isset(self::$routes[$name][0]) and self::$routes[$name][0]=== '^') {
            $is_strict = true;
            $route = self::$routes[$name];
            //in this case remove conditional patterns
            $url = self::parsePattern($route, true);

            //we remove also conditional atoms
            $url = preg_replace('#\(.*\)\?#', '', $route);

            $url = ltrim($url, '^');
            $url = rtrim($url, '$');
            if (preg_match_all('#\(.*\)#U',$url, $matches)) {
                foreach ($params as $key=>$param) {
                    $url = str_replace($matches[0][$key],$param, $url);
                }
            }
            
            if (self::$qs[$name]) {
                $qs = preg_replace('#(&?)'.self::$qs[$name].'#', '', $qs);
            }
            
        //non strict route
        } else {
            $is_strict = false;
            
            //If required we remove other routes (from segments and qs)
            if (count(self::$remove[$name])) {

                foreach (self::$remove[$name] as $route) {

                    if (self::$routes[$route]) {
                        $url = preg_replace('#(\/?)'.self::$routes[$route].'#', '', $url);
                    }
                    if (self::$qs[$route]) {
                        $qs = preg_replace('#(&?)'.self::$qs[$route].'#', '', $qs);
                    }

                }
            }

            //if this route works with uri
            //I check for all params to build the append segment with given params,
            //then I strip current rule and append new one.
            if (self::$routes[$name]) {
                $append =  self::$routes[$name];
                if (preg_match_all('#\(.*\)#U',$append, $matches)) {
                    foreach ($params as $key=>$param) {
                        $append = str_replace($matches[0][$key],$param, $append);
                    }
                }
                $url = preg_replace('#(\/?)'.self::$routes[$name].'#', '', $url);
                $url = $url."/".$append;
                $url = str_replace('//','/',$url);

            }
            
        }

        
        //if this route works on query string
        //I check for all params to buid and "append" or "replace" query string with given params.
        $append = '';
        if (self::$qs[$name]) {
            $append =  self::$qs[$name];
            if (preg_match_all('#\(.*\)#U',$append, $matches)) {
                foreach ($params as $key=>$param) {
                    $append = str_replace($matches[0][$key],$param, $append);
                }
            }
            $qs = preg_replace('#(&?)'.self::$qs[$name].'#', '', $qs);
            $qs = str_replace('&&','&',$qs);
            $qs = rtrim($qs, '&');
            $qs =  $qs .'&'.$append;
            $qs = ltrim($qs, '&');

        }
        if ($is_strict == true) $qs = $append;
        if ($qs != '') $qs = '?'.$qs;
        if ($url == '') $url = '/';
        return $url.$qs;
    }
1093495
private function generateRouteName(): string
    {
        if (!array_key_exists($this->actionName, $this->adminConfiguration->getParameter('actions'))) {
            throw new Exception(
                sprintf('Invalid action name %s for admin %s (available action are: %s)',
                    $this->actionName,
                    $this->adminName,
                    implode(', ', array_keys($this->adminConfiguration->getParameter('actions'))))
            );
        }
        $routeName = RoutingLoader::generateRouteName(
            $this->adminName,
            $this->actionName,
            $this->adminConfiguration->getParameter('routing_name_pattern')
        );

        return $routeName;
    }
1051576
public function getRoute(string $routeKey, array $params = []): string
    {
        $this->checkRouteIsDefined($routeKey);

        return route(
            $this->getAttribute('routes')[$routeKey]['alias'],
            array_merge($this->getAttribute('routes')[$routeKey]['parameters'], $params)
        );
    }
295274
public function getRoute($name)
    {
        if (empty($name)) {
            throw new \InvalidArgumentException("Route name not provided.");
        }

        // TODO: This is not very efficient, maybe find a better way
        foreach ($this->routes as $route) {
            if ($route->getName() === $name) {
                return $route;
            }
        }

        throw new \Exception("Route \"$name\" not found.");
    }
352994
public function pathFor($name, $vars = [], array $options = [])
    {
        if ($name == 'base') {
            return $this->basePath;
        }
        
        foreach ($this->routes as $route) {
            $route->build();
            
            if ($route->name() == $name) {
                if ($path = $this->buildRouteUrl($route, $vars, $options)) {
                    return $path;
                }
            }
        }
        
        $routeParams = [];
        if (is_array($vars)) {
            $routeParams = array_merge($routeParams, $vars);
        } elseif ($vars instanceof Base) {
            $routeParams['record'] = get_class($vars);
            $routeParams['id'] = $vars->id();
        }
        
        $routeParams = implode(', ', array_map(function($name, $val) { return $name . '=>' . $val; }, array_keys($routeParams), $routeParams));
        $message = "Couldn't find route with name '%s' and options { %s }";
        throw new Exception\InvalidArgumentException(sprintf(
            $message,
            $name,
            $routeParams
        ));
    }