From 5eb975ef69c7d2dce080cd67205f08fb211271e5 Mon Sep 17 00:00:00 2001 From: Daniele Alessandri Date: Wed, 11 Dec 2013 12:45:47 +0100 Subject: [PATCH] Improve URI parsing for connection parameters. Using PHP's "parse_str()" to parse the query string is slightly more efficient then our own code especially when the number of fields in the query string grows, with the additional benefit of supporting arrays for values when brackets are present in fieldnames. So after this commit, providing this URI string: $string = 'tcp://127.0.0.1?metavars[]=foo&metavars[]=hoge'; Is equivalent to providing the following named array: $array = [ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'metavars' => ['foo', 'hoge'], ]; Aside from this improvement, the URI parsing behavior has not changed. --- lib/Predis/Connection/ConnectionParameters.php | 10 +++------- .../Connection/ConnectionParametersTest.php | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/Predis/Connection/ConnectionParameters.php b/lib/Predis/Connection/ConnectionParameters.php index 952535f4..34fda0ae 100644 --- a/lib/Predis/Connection/ConnectionParameters.php +++ b/lib/Predis/Connection/ConnectionParameters.php @@ -99,14 +99,10 @@ class ConnectionParameters implements ConnectionParametersInterface } if (isset($parsed['query'])) { - foreach (explode('&', $parsed['query']) as $kv) { - $kv = explode('=', $kv, 2); - if (isset($kv[0], $kv[1])) { - $parsed[$kv[0]] = $kv[1]; - } - } - + parse_str($parsed['query'], $queryarray); unset($parsed['query']); + + $parsed = array_merge($parsed, $queryarray); } return $parsed; diff --git a/tests/Predis/Connection/ConnectionParametersTest.php b/tests/Predis/Connection/ConnectionParametersTest.php index 28661296..7bb9d3cc 100644 --- a/tests/Predis/Connection/ConnectionParametersTest.php +++ b/tests/Predis/Connection/ConnectionParametersTest.php @@ -182,6 +182,7 @@ class ConnectionParametersTest extends PredisTestCase 'host' => '10.10.10.10', 'persistent' => '1', 'foo' => '', + 'bar' => '', ); $this->assertSame($expected, ConnectionParameters::parse($uri)); @@ -204,6 +205,23 @@ class ConnectionParametersTest extends PredisTestCase $this->assertSame($expected, ConnectionParameters::parse($uri)); } + /** + * @group disconnected + */ + public function testParsingURIWhenQueryStringHasBracketsInFieldnames() + { + $uri = 'tcp://10.10.10.10?persistent=1&metavars[]=foo&metavars[]=hoge'; + + $expected = array( + 'scheme' => 'tcp', + 'host' => '10.10.10.10', + 'persistent' => '1', + 'metavars' => array('foo', 'hoge'), + ); + + $this->assertSame($expected, ConnectionParameters::parse($uri)); + } + /** * @group disconnected * @expectedException InvalidArgumentException