Просмотр исходного кода

Apply some minor internal changes to concrete connection classes.

Daniele Alessandri 11 лет назад
Родитель
Сommit
4840736503

+ 11 - 29
lib/Predis/Connection/AbstractConnection.php

@@ -11,6 +11,7 @@
 
 namespace Predis\Connection;
 
+use InvalidArgumentException;
 use Predis\ClientException;
 use Predis\CommunicationException;
 use Predis\NotSupportedException;
@@ -35,7 +36,7 @@ abstract class AbstractConnection implements SingleConnectionInterface
      */
     public function __construct(ConnectionParametersInterface $parameters)
     {
-        $this->parameters = $this->checkParameters($parameters);
+        $this->parameters = $this->assertParameters($parameters);
     }
 
     /**
@@ -52,20 +53,19 @@ abstract class AbstractConnection implements SingleConnectionInterface
      *
      * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
      */
-    protected function checkParameters(ConnectionParametersInterface $parameters)
+    protected function assertParameters(ConnectionParametersInterface $parameters)
     {
-        switch ($parameters->scheme) {
-            case 'unix':
-                if (!isset($parameters->path)) {
-                    throw new \InvalidArgumentException('Missing UNIX domain socket path');
-                }
+        $scheme = $parameters->scheme;
 
-            case 'tcp':
-                return $parameters;
+        if ($scheme !== 'tcp' && $scheme !== 'unix') {
+            throw new InvalidArgumentException("Invalid scheme: $scheme");
+        }
 
-            default:
-                throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
+        if ($scheme === 'unix' && !isset($parameters->path)) {
+            throw new InvalidArgumentException('Missing UNIX domain socket path');
         }
+
+        return $parameters;
     }
 
     /**
@@ -149,24 +149,6 @@ abstract class AbstractConnection implements SingleConnectionInterface
         CommunicationException::handle(new ProtocolException($this, "$message [{$this->parameters->scheme}://{$this->getIdentifier()}]"));
     }
 
-    /**
-     * Helper method to handle not supported connection parameters.
-     *
-     * @param string $option Name of the option.
-     * @param mixed $parameters Parameters used to initialize the connection.
-     */
-    protected function onInvalidOption($option, $parameters = null)
-    {
-        $class = get_called_class();
-        $message = "Invalid option for connection $class: $option";
-
-        if (isset($parameters)) {
-            $message .= sprintf(' [%s => %s]', $option, $parameters->{$option});
-        }
-
-        throw new NotSupportedException($message);
-    }
-
     /**
      * {@inheritdoc}
      */

+ 1 - 1
lib/Predis/Connection/ComposableStreamConnection.php

@@ -33,7 +33,7 @@ class ComposableStreamConnection extends StreamConnection implements ComposableC
         ConnectionParametersInterface $parameters,
         ProtocolProcessorInterface $protocol = null
     ) {
-        $this->parameters = $this->checkParameters($parameters);
+        $this->parameters = $this->assertParameters($parameters);
         $this->protocol = $protocol ?: new TextProtocolProcessor();
     }
 

+ 51 - 31
lib/Predis/Connection/PhpiredisConnection.php

@@ -44,8 +44,6 @@ use Predis\Response;
  */
 class PhpiredisConnection extends AbstractConnection
 {
-    const ERR_MSG_EXTENSION = 'The %s extension must be loaded in order to be able to use this connection class';
-
     private $reader;
 
     /**
@@ -53,10 +51,11 @@ class PhpiredisConnection extends AbstractConnection
      */
     public function __construct(ConnectionParametersInterface $parameters)
     {
-        $this->checkExtensions();
-        $this->initializeReader();
+        $this->assertExtensions();
 
         parent::__construct($parameters);
+
+        $this->reader = $this->createReader();
     }
 
     /**
@@ -73,43 +72,62 @@ class PhpiredisConnection extends AbstractConnection
     /**
      * Checks if the socket and phpiredis extensions are loaded in PHP.
      */
-    private function checkExtensions()
+    protected function assertExtensions()
     {
-        if (!function_exists('socket_create')) {
-            throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'socket'));
+        if (!extension_loaded('sockets')) {
+            throw new NotSupportedException(
+                'The "sockets" extension is required by this connection backend'
+            );
         }
-        if (!function_exists('phpiredis_reader_create')) {
-            throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'phpiredis'));
+
+        if (!extension_loaded('phpiredis')) {
+            throw new NotSupportedException(
+                'The "phpiredis" extension is required by this connection backend'
+            );
         }
     }
 
     /**
      * {@inheritdoc}
      */
-    protected function checkParameters(ConnectionParametersInterface $parameters)
+    protected function assertParameters(ConnectionParametersInterface $parameters)
     {
         if (isset($parameters->persistent)) {
-            $this->onInvalidOption('persistent', $parameters);
+            throw new NotSupportedException(
+                "Persistent connections are not supported by this connection backend"
+            );
         }
 
-        return parent::checkParameters($parameters);
+        return parent::assertParameters($parameters);
     }
 
     /**
-     * Initializes the protocol reader resource.
+     * Creates a new instance of the protocol reader resource.
+     *
+     * @return resource
      */
-    private function initializeReader()
+    private function createReader()
     {
         $reader = phpiredis_reader_create();
 
         phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
         phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
 
-        $this->reader = $reader;
+        return $reader;
+    }
+
+    /**
+     * Returns the underlying protocol reader resource.
+     *
+     * @return resource
+     */
+    protected function getReader()
+    {
+        return $this->reader;
     }
 
     /**
-     * Gets the handler used by the protocol reader to handle status replies.
+     * Returns the handler used by the protocol reader to handle status replies.
      *
      * @return \Closure
      */
@@ -130,15 +148,14 @@ class PhpiredisConnection extends AbstractConnection
     }
 
     /**
-     * Gets the handler used by the protocol reader to handle Redis errors.
+     * Returns the handler used by the protocol reader to handle Redis errors.
      *
-     * @param Boolean $throw_errors Specify if Redis errors throw exceptions.
      * @return \Closure
      */
-    private function getErrorHandler()
+    protected function getErrorHandler()
     {
-        return function ($errorMessage) {
-            return new Response\Error($errorMessage);
+        return function ($payload) {
+            return new Response\Error($payload);
         };
     }
 
@@ -160,18 +177,17 @@ class PhpiredisConnection extends AbstractConnection
      */
     protected function createResource()
     {
-        $parameters = $this->parameters;
-
         $isUnix = $this->parameters->scheme === 'unix';
         $domain = $isUnix ? AF_UNIX : AF_INET;
         $protocol = $isUnix ? 0 : SOL_TCP;
 
         $socket = @call_user_func('socket_create', $domain, SOCK_STREAM, $protocol);
+
         if (!is_resource($socket)) {
             $this->emitSocketError();
         }
 
-        $this->setSocketOptions($socket, $parameters);
+        $this->setSocketOptions($socket, $this->parameters);
 
         return $socket;
     }
@@ -222,7 +238,7 @@ class PhpiredisConnection extends AbstractConnection
      * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
      * @return string
      */
-    private function getAddress(ConnectionParametersInterface $parameters)
+    private static function getAddress(ConnectionParametersInterface $parameters)
     {
         if ($parameters->scheme === 'unix') {
             return $parameters->path;
@@ -234,6 +250,7 @@ class PhpiredisConnection extends AbstractConnection
             if (($addresses = gethostbynamel($host)) === false) {
                 $this->onConnectionError("Cannot resolve the address of $host");
             }
+
             return $addresses[array_rand($addresses)];
         }
 
@@ -255,6 +272,7 @@ class PhpiredisConnection extends AbstractConnection
 
         if (@socket_connect($socket, $host, $parameters->port) === false) {
             $error = socket_last_error();
+
             if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
                 $this->emitSocketError();
             }
@@ -322,6 +340,7 @@ class PhpiredisConnection extends AbstractConnection
             if ($length === $written) {
                 return;
             }
+
             if ($written === false) {
                 $this->onConnectionError('Error while writing bytes to the server');
             }
@@ -338,7 +357,7 @@ class PhpiredisConnection extends AbstractConnection
         $socket = $this->getResource();
         $reader = $this->reader;
 
-        while (($state = phpiredis_reader_get_state($reader)) === PHPIREDIS_READER_STATE_INCOMPLETE) {
+        while (PHPIREDIS_READER_STATE_INCOMPLETE === $state = phpiredis_reader_get_state($reader)) {
             if (@socket_recv($socket, $buffer, 4096, 0) === false || $buffer === '') {
                 $this->emitSocketError();
             }
@@ -358,9 +377,10 @@ class PhpiredisConnection extends AbstractConnection
      */
     public function writeCommand(CommandInterface $command)
     {
-        $cmdargs = $command->getArguments();
-        array_unshift($cmdargs, $command->getId());
-        $this->write(phpiredis_format_command($cmdargs));
+        $arguments = $command->getArguments();
+        array_unshift($arguments, $command->getId());
+
+        $this->write(phpiredis_format_command($arguments));
     }
 
     /**
@@ -368,7 +388,7 @@ class PhpiredisConnection extends AbstractConnection
      */
     public function __wakeup()
     {
-        $this->checkExtensions();
-        $this->initializeReader();
+        $this->assertExtensions();
+        $this->reader = $this->createReader();
     }
 }

+ 30 - 16
lib/Predis/Connection/PhpiredisStreamConnection.php

@@ -54,10 +54,11 @@ class PhpiredisStreamConnection extends StreamConnection
      */
     public function __construct(ConnectionParametersInterface $parameters)
     {
-        $this->checkExtensions();
-        $this->initializeReader();
+        $this->assertExtensions();
 
         parent::__construct($parameters);
+
+        $this->reader = $this->createReader();
     }
 
     /**
@@ -73,30 +74,42 @@ class PhpiredisStreamConnection extends StreamConnection
     /**
      * Checks if the phpiredis extension is loaded in PHP.
      */
-    protected function checkExtensions()
+    private function assertExtensions()
     {
-        if (!function_exists('phpiredis_reader_create')) {
+        if (!extension_loaded('phpiredis')) {
             throw new NotSupportedException(
-                'The phpiredis extension must be loaded in order to be able to use this connection class'
+                'The "phpiredis" extension is required by this connection backend'
             );
         }
     }
 
     /**
-     * Initializes the protocol reader resource.
+     * Creates a new instance of the protocol reader resource.
+     *
+     * @return resource
      */
-    protected function initializeReader()
+    private function createReader()
     {
         $reader = phpiredis_reader_create();
 
         phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
         phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
 
-        $this->reader = $reader;
+        return $reader;
+    }
+
+    /**
+     * Returns the underlying protocol reader resource.
+     *
+     * @return resource
+     */
+    protected function getReader()
+    {
+        return $this->reader;
     }
 
     /**
-     * Gets the handler used by the protocol reader to handle status replies.
+     * Returns the handler used by the protocol reader to handle status replies.
      *
      * @return \Closure
      */
@@ -117,9 +130,8 @@ class PhpiredisStreamConnection extends StreamConnection
     }
 
     /**
-     * Gets the handler used by the protocol reader to handle Redis errors.
+     * Returns the handler used by the protocol reader to handle Redis errors.
      *
-     * @param Boolean $throw_errors Specify if Redis errors throw exceptions.
      * @return \Closure
      */
     protected function getErrorHandler()
@@ -142,6 +154,7 @@ class PhpiredisStreamConnection extends StreamConnection
 
             if ($buffer === false || $buffer === '') {
                 $this->onConnectionError('Error while reading bytes from the server');
+
                 return;
             }
 
@@ -160,9 +173,10 @@ class PhpiredisStreamConnection extends StreamConnection
      */
     public function writeCommand(CommandInterface $command)
     {
-        $cmdargs = $command->getArguments();
-        array_unshift($cmdargs, $command->getId());
-        $this->writeBytes(phpiredis_format_command($cmdargs));
+        $arguments = $command->getArguments();
+        array_unshift($arguments, $command->getId());
+
+        $this->writeBytes(phpiredis_format_command($arguments));
     }
 
     /**
@@ -170,7 +184,7 @@ class PhpiredisStreamConnection extends StreamConnection
      */
     public function __wakeup()
     {
-        $this->checkExtensions();
-        $this->initializeReader();
+        $this->assertExtensions();
+        $this->reader = $this->createReader();
     }
 }

+ 5 - 3
lib/Predis/Connection/StreamConnection.php

@@ -159,6 +159,7 @@ class StreamConnection extends AbstractConnection
             if ($length === $written) {
                 return;
             }
+
             if ($written === false || $written === 0) {
                 $this->onConnectionError('Error while writing bytes to the server');
             }
@@ -197,6 +198,7 @@ class StreamConnection extends AbstractConnection
 
             case '$':    // bulk
                 $size = (int) $payload;
+
                 if ($size === -1) {
                     return null;
                 }
@@ -248,13 +250,13 @@ class StreamConnection extends AbstractConnection
      */
     public function writeCommand(CommandInterface $command)
     {
-        $commandId = $command->getId();
+        $commandID = $command->getId();
         $arguments = $command->getArguments();
 
-        $cmdlen = strlen($commandId);
+        $cmdlen = strlen($commandID);
         $reqlen = count($arguments) + 1;
 
-        $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandId}\r\n";
+        $buffer = "*{$reqlen}\r\n\${$cmdlen}\r\n{$commandID}\r\n";
 
         for ($i = 0; $i < $reqlen - 1; $i++) {
             $argument = $arguments[$i];

+ 25 - 21
lib/Predis/Connection/WebdisConnection.php

@@ -11,6 +11,7 @@
 
 namespace Predis\Connection;
 
+use InvalidArgumentException;
 use Predis\NotSupportedException;
 use Predis\Command\CommandInterface;
 use Predis\Connection\ConnectionException;
@@ -44,8 +45,6 @@ use Predis\Response;
  */
 class WebdisConnection implements SingleConnectionInterface
 {
-    const ERR_MSG_EXTENSION = 'The %s extension must be loaded in order to be able to use this connection class';
-
     private $parameters;
     private $resource;
     private $reader;
@@ -55,15 +54,15 @@ class WebdisConnection implements SingleConnectionInterface
      */
     public function __construct(ConnectionParametersInterface $parameters)
     {
-        $this->checkExtensions();
+        $this->assertExtensions();
 
         if ($parameters->scheme !== 'http') {
-            throw new \InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
+            throw new InvalidArgumentException("Invalid scheme: {$parameters->scheme}");
         }
 
         $this->parameters = $parameters;
-        $this->resource = $this->initializeCurl($parameters);
-        $this->reader = $this->initializeReader($parameters);
+        $this->resource = $this->createCurl($parameters);
+        $this->reader = $this->createReader($parameters);
     }
 
     /**
@@ -88,14 +87,18 @@ class WebdisConnection implements SingleConnectionInterface
     /**
      * Checks if the cURL and phpiredis extensions are loaded in PHP.
      */
-    private function checkExtensions()
+    private function assertExtensions()
     {
-        if (!function_exists('curl_init')) {
-            throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'curl'));
+        if (!extension_loaded('curl')) {
+            throw new NotSupportedException(
+                'The "curl" extension is required by this connection backend'
+            );
         }
 
-        if (!function_exists('phpiredis_reader_create')) {
-            throw new NotSupportedException(sprintf(self::ERR_MSG_EXTENSION, 'phpiredis'));
+        if (!extension_loaded('phpiredis')) {
+            throw new NotSupportedException(
+                'The "phpiredis" extension is required by this connection backend'
+            );
         }
     }
 
@@ -105,7 +108,7 @@ class WebdisConnection implements SingleConnectionInterface
      * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
      * @return resource
      */
-    private function initializeCurl(ConnectionParametersInterface $parameters)
+    private function createCurl(ConnectionParametersInterface $parameters)
     {
         $options = array(
             CURLOPT_FAILONERROR => true,
@@ -131,7 +134,7 @@ class WebdisConnection implements SingleConnectionInterface
      * @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
      * @return resource
      */
-    private function initializeReader(ConnectionParametersInterface $parameters)
+    private function createReader(ConnectionParametersInterface $parameters)
     {
         $reader = phpiredis_reader_create();
 
@@ -160,8 +163,8 @@ class WebdisConnection implements SingleConnectionInterface
      */
     protected function getErrorHandler()
     {
-        return function ($errorMessage) {
-            return new Response\Error($errorMessage);
+        return function ($payload) {
+            return new Response\Error($payload);
         };
     }
 
@@ -211,7 +214,7 @@ class WebdisConnection implements SingleConnectionInterface
      */
     protected function getCommandId(CommandInterface $command)
     {
-        switch (($commandId = $command->getId())) {
+        switch ($commandID = $command->getId()) {
             case 'AUTH':
             case 'SELECT':
             case 'MULTI':
@@ -220,10 +223,10 @@ class WebdisConnection implements SingleConnectionInterface
             case 'UNWATCH':
             case 'DISCARD':
             case 'MONITOR':
-                throw new NotSupportedException("Disabled command: {$command->getId()}");
+                throw new NotSupportedException("Disabled command: $commandID");
 
             default:
-                return $commandId;
+                return $commandID;
         }
     }
 
@@ -263,6 +266,7 @@ class WebdisConnection implements SingleConnectionInterface
         if (curl_exec($resource) === false) {
             $error = curl_error($resource);
             $errno = curl_errno($resource);
+
             throw new ConnectionException($this, trim($error), $errno);
         }
 
@@ -326,10 +330,10 @@ class WebdisConnection implements SingleConnectionInterface
      */
     public function __wakeup()
     {
-        $this->checkExtensions();
+        $this->assertExtensions();
         $parameters = $this->getParameters();
 
-        $this->resource = $this->initializeCurl($parameters);
-        $this->reader = $this->initializeReader($parameters);
+        $this->resource = $this->createCurl($parameters);
+        $this->reader = $this->createReader($parameters);
     }
 }