Remove unwanted query parameters from normalized URLs
This commit is contained in:
parent
12a6b8f6b3
commit
6ccd564d56
2 changed files with 34 additions and 16 deletions
29
helpers.php
29
helpers.php
|
@ -126,20 +126,33 @@ if (! function_exists('normalize_url')) {
|
|||
|
||||
// Sort GET params alphabetically, not because the RFC requires it but because it's cool!
|
||||
if (isset($url['query'])) {
|
||||
if (preg_match('/&/', $url['query'])) {
|
||||
$s = explode('&', $url['query']);
|
||||
$url['query'] = '';
|
||||
sort($s);
|
||||
foreach ($s as $z) {
|
||||
$url['query'] .= "{$z}&";
|
||||
$queries = explode('&', $url['query']);
|
||||
$url['query'] = '';
|
||||
sort($queries);
|
||||
foreach ($queries as $query) {
|
||||
//lets drop query params we don’t want
|
||||
$key = stristr($query, '=', true);
|
||||
if (queryKeyIsBanned($key) === false) {
|
||||
$url['query'] .= "{$query}&";
|
||||
}
|
||||
$url['query'] = preg_replace('/&\Z/', '', $url['query']);
|
||||
}
|
||||
$newUrl .= "?{$url['query']}";
|
||||
$url['query'] = preg_replace('/&\Z/', '', $url['query']);
|
||||
if ($url['query'] !== '') {
|
||||
$newUrl .= "?{$url['query']}";
|
||||
}
|
||||
}
|
||||
|
||||
return $newUrl;
|
||||
}
|
||||
|
||||
function queryKeyIsBanned(string $key): bool
|
||||
{
|
||||
$bannedKeys = [
|
||||
'ref_src',
|
||||
];
|
||||
|
||||
return in_array($key, $bannedKeys);
|
||||
}
|
||||
}
|
||||
|
||||
// sourced from https://stackoverflow.com/a/9776726
|
||||
|
|
|
@ -12,14 +12,6 @@ class HelpersTest extends TestCase
|
|||
$this->assertEquals(normalize_url(normalize_url($input)), normalize_url($input));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider urlProvider
|
||||
*/
|
||||
public function test_normalize_url($input, $output)
|
||||
{
|
||||
$this->assertEquals($output, normalize_url($input));
|
||||
}
|
||||
|
||||
public function urlProvider()
|
||||
{
|
||||
return [
|
||||
|
@ -27,9 +19,22 @@ class HelpersTest extends TestCase
|
|||
['https://example.org:443/', 'https://example.org'],
|
||||
['http://www.foo.bar/index.php/', 'http://www.foo.bar'],
|
||||
['https://example.org/?foo=bar&baz=true', 'https://example.org?baz=true&foo=bar'],
|
||||
[
|
||||
'http://example.org/?ref_src=twcamp^share|twsrc^ios|twgr^software.studioh.Indigenous.share-micropub',
|
||||
'http://example.org',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider urlProvider
|
||||
* @group temp
|
||||
*/
|
||||
public function test_normalize_url($input, $output)
|
||||
{
|
||||
$this->assertEquals($output, normalize_url($input));
|
||||
}
|
||||
|
||||
public function test_pretty_print_json()
|
||||
{
|
||||
$json = <<<JSON
|
||||
|
|
Loading…
Add table
Reference in a new issue