PHPRouter\Router::generate PHP Method

generate() public method

Reverse route a named route
public generate ( $routeName, array $params = [] ) : string
$routeName
$params array Optional array of parameters to use in URL
return string The url to the route
    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("/:(\\w+)/", $params[$key], $url, 1);
                }
            }
        }
        return $url;
    }