Skip to content

Commit

Permalink
Merge query params instead of just appending them
Browse files Browse the repository at this point in the history
  • Loading branch information
riasvdv committed Dec 27, 2024
1 parent 1c68573 commit e2a81e4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/Http/Middleware/HandleNotFound.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@ public function handle(Request $request, Closure $next)
abort(410);
}

$destination = $this->cachedRedirects[$site->handle()][$url]['destination'];

return redirect(
$this->cachedRedirects[$site->handle()][$url]['destination'].(config('statamic.redirect.preserve_query_strings') && $request->getQueryString() ? '?'.$request->getQueryString() : ''),
$this->mergeQuery($request, $destination),
$this->cachedRedirects[$site->handle()][$url]['type'],
);
}
Expand All @@ -74,7 +76,7 @@ public function handle(Request $request, Closure $next)
}

return redirect(
$redirect->destination().(config('statamic.redirect.preserve_query_strings') && $request->getQueryString() ? '?'.$request->getQueryString() : ''),
$this->mergeQuery($request, $redirect->destination()),
$redirect->type()
);
} catch (\Exception $e) {
Expand Down Expand Up @@ -135,4 +137,30 @@ private function cacheNewRedirect(\Statamic\Sites\Site $site, RedirectContract $

Cache::put('statamic.redirect.redirects', $this->cachedRedirects);
}

public function mergeQuery(Request $request, string $destination): string
{
if (! config('statamic.redirect.preserve_query_strings')) {
return $destination;
}

if (! $request->getQueryString()) {
return $destination;
}

$destination_parsed = parse_url($destination);
$destination_query = [];

if (isset($destination_parsed['query'])) {
parse_str($destination_parsed['query'], $destination_query);
}

$query = array_merge($destination_query, $request->query());

if (count($query)) {
$destination .= '?' . http_build_query($query);
}

return $destination;
}
}
21 changes: 21 additions & 0 deletions tests/Feature/Middleware/HandleNotFoundTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,27 @@ public function it_can_preserve_query_strings()
$this->assertTrue($response->isRedirect(url('/fr?lang=fr')));
}

public function it_merges_query_strings()
{
config()->set('statamic.redirect.preserve_query_strings', true);

Redirect::make()
->source('/abc')
->destination('/nl')
->save();

Redirect::make()
->source('/abc?another=value')
->destination('/fr')
->save();

$response = $this->middleware->handle(Request::create('/abc', 'GET', ['lang' => 'nl']), function () {
return (new Response('', 404));
});

$this->assertTrue($response->isRedirect(url('/nl?lang=nl&another=value')));
}

/**
* @test
*/
Expand Down

0 comments on commit e2a81e4

Please sign in to comment.