Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leftover params label:enhancement #251

Open
infira opened this issue Apr 7, 2020 · 0 comments
Open

Leftover params label:enhancement #251

infira opened this issue Apr 7, 2020 · 0 comments

Comments

@infira
Copy link

infira commented Apr 7, 2020

It would be cool if on ->generate() params which was not used are added to as query string

public function generate($routeName, array $params = array()) {
	
	// Check if named route exists
	if(!isset($this->namedRoutes[$routeName])) {
		throw new \Exception("Route '{$routeName}' does not exist.");
	}
	
	// Replace named parameters
	$route = $this->namedRoutes[$routeName];
	
	// prepend base path to route url again
	$url = $this->basePath . $route;
	
	if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
		
		foreach($matches as $match) {
			list($block, $pre, $type, $param, $optional) = $match;
			
			if ($pre) {
				$block = substr($block, 1);
			}
			
			if(isset($params[$param])) {
				$url = str_replace($block, $params[$param], $url);
				unset($params[$param]);//set param as used
			} elseif ($optional) {
				$url = str_replace($pre . $block, '', $url);
			}
		}
	}
	
	if (count($params) > 0) //check is any params left to build url with
	{
		$url .= '?'.http_build_query($params);
	}
	
	return $url;
}

then

$alto->map( 'GET|POST', '/users/[i:id]/','handleContactForm');
$alto->generate('handleContactForm',['id'=>10,'myCustomParam'=>'blaah']);
// will outputs /users/10?myCustomParam=blaah
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant