Merge pull request #60 from shikorism/fix/56-broken-normalize

This commit is contained in:
shibafu 2019-01-19 02:27:07 +09:00 committed by GitHub
commit 8aa2e6a779
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 74 additions and 4 deletions

View File

@ -52,12 +52,25 @@ class Formatter
$url = preg_replace('~/#!/~u', '/', $url);
// Sort query parameters
$query = parse_url($url, PHP_URL_QUERY);
if (!empty($query)) {
$url = str_replace_last('?' . $query, '', $url);
parse_str($query, $params);
$parts = parse_url($url);
if (!empty($parts['query'])) {
// Remove query parameters
$url = str_replace_last('?' . $parts['query'], '', $url);
if (!empty($parts['fragment'])) {
// Remove fragment identifier
$url = str_replace_last('#' . $parts['fragment'], '', $url);
} else {
// "http://example.com/?query#" の場合 $parts['fragment'] は unset になるので、個別に判定して除去する必要がある
$url = preg_replace('/#\z/u', '', $url);
}
parse_str($parts['query'], $params);
ksort($params);
$url = $url . '?' . http_build_query($params);
if (!empty($parts['fragment'])) {
$url .= '#' . $parts['fragment'];
}
}
return $url;

View File

@ -0,0 +1,57 @@
<?php
namespace Tests\Unit\Utilities;
use App\Utilities\Formatter;
use Tests\TestCase;
class FormatterTest extends TestCase
{
public function testNormalizeUrlWithoutQuery()
{
$formatter = new Formatter();
$url = 'http://example.com/path/to';
$this->assertEquals($url, $formatter->normalizeUrl($url));
}
public function testNormalizeUrlWithSortedQuery()
{
$formatter = new Formatter();
$url = 'http://example.com/path/to?foo=bar&hoge=fuga';
$this->assertEquals($url, $formatter->normalizeUrl($url));
}
public function testNormalizeUrlWithUnsortedQuery()
{
$formatter = new Formatter();
$url = 'http://example.com/path/to?hoge=fuga&foo=bar';
$this->assertEquals('http://example.com/path/to?foo=bar&hoge=fuga', $formatter->normalizeUrl($url));
}
public function testNormalizeUrlWithSortedQueryAndFragment()
{
$formatter = new Formatter();
$url = 'http://example.com/path/to?foo=bar&hoge=fuga#fragment';
$this->assertEquals($url, $formatter->normalizeUrl($url));
}
public function testNormalizeUrlWithFragment()
{
$formatter = new Formatter();
$url = 'http://example.com/path/to#fragment';
$this->assertEquals($url, $formatter->normalizeUrl($url));
}
public function testNormalizeUrlWithSortedQueryAndZeroLengthFragment()
{
$formatter = new Formatter();
$url = 'http://example.com/path/to?foo=bar&hoge=fuga#';
$this->assertEquals('http://example.com/path/to?foo=bar&hoge=fuga', $formatter->normalizeUrl($url));
}
}