diff --git a/CHANGELOG.md b/CHANGELOG.md index 105485f1..64dd8f0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ All Notable changes to `League\Uri\Components` will be documented in this file - `Modifier::appendQueryParameters` - `Modifier::mergeQueryParameters` - `Modifier::removeQueryParameters` +- `Modifier::removeQueryParametersIndices` ### Fixed diff --git a/Modifier.php b/Modifier.php index 12dd49eb..9ddc4675 100644 --- a/Modifier.php +++ b/Modifier.php @@ -250,6 +250,25 @@ public function removeEmptyQueryPairs(): static )); } + /** + * Returns an instance where numeric indices associated to PHP's array like key are removed. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the query component normalized so that numeric indexes + * are removed from the pair key value. + * + * ie.: toto[3]=bar[3]&foo=bar becomes toto[]=bar[3]&foo=bar + */ + public function removeQueryParameterIndices(): static + { + return new static($this->uri->withQuery( + static::normalizeComponent( + Query::fromUri($this->uri)->withoutNumericIndices()->value(), + $this->uri + ) + )); + } + /********************************* * Host modifier methods *********************************/ diff --git a/ModifierTest.php b/ModifierTest.php index b47dae18..3e9aa1ae 100644 --- a/ModifierTest.php +++ b/ModifierTest.php @@ -212,6 +212,32 @@ public static function removeParamsProvider(): array ]; } + /** + * @dataProvider removeQueryParameterIndicesProvider + */ + public function testWithoutQueryParameterIndices(string $uri, string $expected): void + { + self::assertSame($expected, Modifier::from($uri)->removeQueryParameterIndices()->getUri()->getQuery()); + } + + public static function removeQueryParameterIndicesProvider(): array + { + return [ + [ + 'uri' => 'http://example.com?foo=bar', + 'expected' => 'foo=bar', + ], + [ + 'uri' => 'http://example.com?foo[0]=bar&foo[1]=baz', + 'expected' => 'foo%5B%5D=bar&foo%5B%5D=baz', + ], + [ + 'uri' => 'http://example.com?foo[not-remove]=bar&foo[1]=baz', + 'expected' => 'foo%5Bnot-remove%5D=bar&foo%5B%5D=baz', + ], + ]; + } + /** * @dataProvider removeEmptyPairsProvider */