Rareloop / lumberjack-core

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How do I make the router work with a query string?

kristiwr opened this issue · comments

What code do I need for the router to recognize an optional query string? I specifically need a query string because it will be parsed by JavaScript on the page. I tried creating two routes, one with a query string parameter and one without. The one without the query string works fine, but when the query string is present the router doesn't match the route. I looked on the Router page in the documentation but couldn't find anything about this. Can you help?

My code in routes.php:

Router::get(
    "{type}-selector/",
    "App\Controllers\SelectorController@handle"
)->name(ROUTE_SELECTOR);

Router::get(
    "{type}-selector/{query}",
    "App\Controllers\SelectorController@handle"
)->name(ROUTE_SELECTOR_WITH_QUERY);

And from the view model that uses the route helper to generate a selector URL:

$more_url = route(ROUTE_SELECTOR_WITH_QUERY, [
    "type" => $this->type,
    "query" => "?" . http_build_query($this->specifications)
]);

(I tried removing the ? from the query param and hardcoding it into the route, but that didn't fix it.)

The route helper generates this URL. It's an absolute URL, but I've made it relative here for privacy reasons.

/connector-selector/?foo=foo&bar=bar&baz=baz/

The handle method signature in the selector controller looks like this:

public function handle(string $type, string $query = ""): TimberResponse

However, the router doesn't match the link that the route helper generates.

It seems like the issue arises from AltoRouter->match() via Rareloop\Router\Router->match(). Router is only passing the URI path to AltoRouter, and AltoRouter->match() appears to lack support for query strings.

Router line 161:
$altoRoute = $this->altoRouter->match($request->getUri()->getPath(), $request->getMethod());

I'm going to try converting the route to use Lumberjack-style parameters, and have the selector view model use them to generate a traditional query string to embed in a data attribute in the view. Then my JavaScript app could reference that attribute.

That worked! It would be a good idea to add a note to the documentation for the router and route helper saying that query strings are not supported - and perhaps even a check in the route helper that throws an exception if a param value is a query string.