diff --git a/src/Monolog/Handler/SyslogUdp/UdpSocket.php b/src/Monolog/Handler/SyslogUdp/UdpSocket.php index 30b5186b..dbd8ef69 100644 --- a/src/Monolog/Handler/SyslogUdp/UdpSocket.php +++ b/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 } } + /** + * @return resource|Socket + */ + protected function getSocket() + { + if (null !== $this->socket) { + return $this->socket; + } + + $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 { - 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'); - } - socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port); + socket_sendto($this->getSocket(), $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port); } protected function assembleMessage(string $line, string $header): string diff --git a/tests/Monolog/Handler/UdpSocketTest.php b/tests/Monolog/Handler/UdpSocketTest.php index c14fa8d4..98c65dc2 100644 --- a/tests/Monolog/Handler/UdpSocketTest.php +++ b/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");