Explorar el Código

Minor optimizations for the parsing of URI parameters.

Using list() with the warning suppressor is slower than using isset()
to check the presence of the first two elements of the array returned
by explode(). This also allow us to skip incomplete query string pairs
when parsing the URI string.

We have also changed the exception being thrown on invalid URIs to a
more appropriate one.
Daniele Alessandri hace 11 años
padre
commit
5e90e615b1

+ 7 - 5
lib/Predis/Connection/ConnectionParameters.php

@@ -11,7 +11,7 @@
 
 namespace Predis\Connection;
 
-use Predis\ClientException;
+use InvalidArgumentException;
 
 /**
  * Handles parsing and validation of connection parameters.
@@ -113,14 +113,16 @@ class ConnectionParameters implements ConnectionParametersInterface
             $uri = str_ireplace('unix:///', 'unix://localhost/', $uri);
         }
 
-        if (!($parsed = @parse_url($uri)) || !isset($parsed['host'])) {
-            throw new ClientException("Invalid URI: $uri");
+        if (!($parsed = parse_url($uri)) || !isset($parsed['host'])) {
+            throw new InvalidArgumentException("Invalid parameters URI: $uri");
         }
 
         if (isset($parsed['query'])) {
             foreach (explode('&', $parsed['query']) as $kv) {
-                @list($k, $v) = explode('=', $kv);
-                $parsed[$k] = $v;
+                $kv = explode('=', $kv);
+                if (isset($kv[0], $kv[1])) {
+                    $parsed[$kv[0]] = $kv[1];
+                }
             }
 
             unset($parsed['query']);

+ 19 - 2
tests/Predis/Connection/ConnectionParametersTest.php

@@ -159,8 +159,25 @@ class ParametersTest extends StandardTestCase
 
     /**
      * @group disconnected
-     * @expectedException Predis\ClientException
-     * @expectedExceptionMessage Invalid URI: tcp://invalid:uri
+     */
+    public function testParsingURIWithIncompletePairInQueryString()
+    {
+        $uri = 'tcp://10.10.10.10?persistent=1&foo=&bar';
+
+        $expected = array(
+            'scheme' => 'tcp',
+            'host' => '10.10.10.10',
+            'persistent' => '1',
+            'foo' => '',
+        );
+
+        $this->assertSame($expected, ConnectionParameters::parse($uri));
+    }
+
+    /**
+     * @group disconnected
+     * @expectedException InvalidArgumentException
+     * @expectedExceptionMessage Invalid parameters URI: tcp://invalid:uri
      */
     public function testParsingURIThrowOnInvalidURI()
     {