Переглянути джерело

Allow UdpSocket to reconnect after close()

Jordi Boggiano 3 роки тому
батько
коміт
5d43fd52d3

+ 27 - 13
src/Monolog/Handler/SyslogUdp/UdpSocket.php

@@ -23,20 +23,12 @@ class UdpSocket
     /** @var int */
     protected $port;
     /** @var resource|Socket|null */
-    protected $socket;
+    protected $socket = null;
 
     public function __construct(string $ip, int $port = 514)
     {
         $this->ip = $ip;
         $this->port = $port;
-        $domain = AF_INET;
-        $protocol = SOL_UDP;
-        // Check if we are using unix sockets.
-        if ($port === 0) {
-            $domain = AF_UNIX;
-            $protocol = IPPROTO_IP;
-        }
-        $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null;
     }
 
     /**
@@ -57,12 +49,34 @@ class UdpSocket
         }
     }
 
-    protected function send(string $chunk): void
+    /**
+     * @return resource|Socket
+     */
+    protected function getSocket()
     {
-        if (!is_resource($this->socket) && !$this->socket instanceof Socket) {
-            throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
+        if (null !== $this->socket) {
+            return $this->socket;
         }
-        socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
+
+        $domain = AF_INET;
+        $protocol = SOL_UDP;
+        // Check if we are using unix sockets.
+        if ($this->port === 0) {
+            $domain = AF_UNIX;
+            $protocol = IPPROTO_IP;
+        }
+
+        $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null;
+        if (null === $this->socket) {
+            throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create');
+        }
+
+        return $this->socket;
+    }
+
+    protected function send(string $chunk): void
+    {
+        socket_sendto($this->getSocket(), $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
     }
 
     protected function assembleMessage(string $line, string $header): string

+ 1 - 3
tests/Monolog/Handler/UdpSocketTest.php

@@ -58,10 +58,8 @@ class UdpSocketTest extends TestCase
         $socket->close();
     }
 
-    public function testWriteAfterCloseErrors()
+    public function testWriteAfterCloseReopened()
     {
-        $this->expectException(\RuntimeException::class);
-
         $socket = new UdpSocket('127.0.0.1', 514);
         $socket->close();
         $socket->write('foo', "HEADER");