Filter used GET parameters and pass them to the current link

Sometimes you hack something together and if a special get parameter is used something should appear different on the current page. And under certain circumstances you also want to modify all generated links to pass those paramters further. Fortunaltly SiteTree has a extension hook in getRelativeLink(), which is responsible for generating the current link. So we can hook in here.

A first version in our DataExtension might look like:

public function updateRelativeLink(&$base, &$action) {

	foreach(['foo', 'bar'] as $getParam) {
		if (Controller::curr()->getRequest->getVar($getParam)) {
			$additionalParams[] =  $getParam . '=' . $request->getVar($getParam);
		}
	}

	$base = Controller::join_links($base, '?' . join('&', $additionalParams));

}

which is already working but not really elegant, as it has two levels deep nesting (foreach and if). So any chance to get it better, and maybe faster with built-in php functions?

We can try a functional approach to filter the get vars and use array_map() to build the strings we want to add to the current $Link. Unfortunately array_map() doesn't work with $key=>$value out of the box, so we need to use array_key() to get an array with the keys and pass both arrays to array_map(), which leads us to this version:

public function updateRelativeLink(&$base, &$action) {
	$usedParams = array_intersect_key(
		Controller::curr()->getRequest()->getVars(),
		array_flip(['foo', 'bar'])
	);

	$additionalParams = array_map(
		function($k, $v)  {return $k . '=' . $v;},
		array_keys($usedParams),
		$usedParams
	);

	$base = Controller::join_links($base, '?' . join('&', $additionalParams));

}

 

 

Rate this post

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments