Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php declare(strict_types=1);
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
use Monolog\Utils;
15
use Socket;
16
 
17
class UdpSocket
18
{
19
    protected const DATAGRAM_MAX_LENGTH = 65023;
20
 
21
    /** @var string */
22
    protected $ip;
23
    /** @var int */
24
    protected $port;
25
    /** @var resource|Socket|null */
26
    protected $socket = null;
27
 
28
    public function __construct(string $ip, int $port = 514)
29
    {
30
        $this->ip = $ip;
31
        $this->port = $port;
32
    }
33
 
34
    /**
35
     * @param  string $line
36
     * @param  string $header
37
     * @return void
38
     */
39
    public function write($line, $header = "")
40
    {
41
        $this->send($this->assembleMessage($line, $header));
42
    }
43
 
44
    public function close(): void
45
    {
46
        if (is_resource($this->socket) || $this->socket instanceof Socket) {
47
            socket_close($this->socket);
48
            $this->socket = null;
49
        }
50
    }
51
 
52
    /**
53
     * @return resource|Socket
54
     */
55
    protected function getSocket()
56
    {
57
        if (null !== $this->socket) {
58
            return $this->socket;
59
        }
60
 
61
        $domain = AF_INET;
62
        $protocol = SOL_UDP;
63
        // Check if we are using unix sockets.
64
        if ($this->port === 0) {
65
            $domain = AF_UNIX;
66
            $protocol = IPPROTO_IP;
67
        }
68
 
69
        $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null;
70
        if (null === $this->socket) {
71
            throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create');
72
        }
73
 
74
        return $this->socket;
75
    }
76
 
77
    protected function send(string $chunk): void
78
    {
79
        socket_sendto($this->getSocket(), $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
80
    }
81
 
82
    protected function assembleMessage(string $line, string $header): string
83
    {
84
        $chunkSize = static::DATAGRAM_MAX_LENGTH - strlen($header);
85
 
86
        return $header . Utils::substr($line, 0, $chunkSize);
87
    }
88
}