]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php
MediaWiki 1.30.2
[autoinstallsdev/mediawiki.git] / vendor / monolog / monolog / src / Monolog / Handler / SyslogUdp / UdpSocket.php
1 <?php
2
3 /*
4  * This file is part of the Monolog package.
5  *
6  * (c) Jordi Boggiano <j.boggiano@seld.be>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Monolog\Handler\SyslogUdp;
13
14 class UdpSocket
15 {
16     const DATAGRAM_MAX_LENGTH = 65023;
17
18     protected $ip;
19     protected $port;
20     protected $socket;
21
22     public function __construct($ip, $port = 514)
23     {
24         $this->ip = $ip;
25         $this->port = $port;
26         $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
27     }
28
29     public function write($line, $header = "")
30     {
31         $this->send($this->assembleMessage($line, $header));
32     }
33
34     public function close()
35     {
36         if (is_resource($this->socket)) {
37             socket_close($this->socket);
38             $this->socket = null;
39         }
40     }
41
42     protected function send($chunk)
43     {
44         if (!is_resource($this->socket)) {
45             throw new \LogicException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
46         }
47         socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
48     }
49
50     protected function assembleMessage($line, $header)
51     {
52         $chunkSize = self::DATAGRAM_MAX_LENGTH - strlen($header);
53
54         return $header . substr($line, 0, $chunkSize);
55     }
56 }