Browse Source

Socket connect works with unix file sockets using port null

Jorge González 6 years ago
parent
commit
e8f473cb4a
2 changed files with 53 additions and 2 deletions
  1. 29 2
      src/Network/Socket.php
  2. 24 0
      tests/TestCase/Network/SocketTest.php

+ 29 - 2
src/Network/Socket.php

@@ -161,8 +161,12 @@ class Socket
         }
 
         set_error_handler([$this, '_connectionErrorHandler']);
-        $this->connection = stream_socket_client(
-            $scheme . $this->_config['host'] . ':' . $this->_config['port'],
+        $remoteSocketTarget = $scheme . $this->_config['host'];
+        if ($this->_config['port'] !== null) {
+            $remoteSocketTarget .= ':' . $this->_config['port'];
+        }
+        $this->connection = $this->_getStreamSocketClient(
+            $remoteSocketTarget,
             $errNum,
             $errStr,
             $this->_config['timeout'],
@@ -190,6 +194,29 @@ class Socket
     }
 
     /**
+     * Create a stream socket client. Mock utility.
+     *
+     * @param string $remoteSocketTarget remote socket
+     * @param int $errNum error number
+     * @param string $errStr error string
+     * @param int $timeout timeout
+     * @param int $connectAs flags
+     * @param resource $context context
+     * @return bool|resource
+     */
+    protected function _getStreamSocketClient($remoteSocketTarget, &$errNum, &$errStr, $timeout, $connectAs, $context)
+    {
+        return stream_socket_client(
+            $remoteSocketTarget,
+            $errNum,
+            $errStr,
+            $timeout,
+            $connectAs,
+            $context
+        );
+    }
+
+    /**
      * Configure the SSL context options.
      *
      * @param string $host The host name being connected to.

+ 24 - 0
tests/TestCase/Network/SocketTest.php

@@ -486,4 +486,28 @@ class SocketTest extends TestCase
         $this->assertArrayNotHasKey('ssl_verify_host', $socket->getConfig());
         $this->assertArrayNotHasKey('ssl_verify_depth', $socket->getConfig());
     }
+
+    /**
+     * test connect to a unix file socket
+     *
+     * @return void
+     */
+    public function testConnectToUnixFileSocket()
+    {
+        $socketName = 'unix:///tmp/test.socket';
+        $socket = $this->getMockBuilder(Socket::class)
+            ->setMethods(['_getStreamSocketClient'])
+            ->getMock();
+        $socket->expects($this->once())
+            ->method('_getStreamSocketClient')
+            ->with('unix:///tmp/test.socket', null, null, 1)
+            ->willReturn(false);
+        $socket->setConfig([
+            'host' => $socketName,
+            'port' => null,
+            'timeout' => 1,
+            'persistent' => true,
+        ]);
+        $socket->connect();
+    }
 }