Passed
Pull Request — master (#95)
by Dmitriy
02:51
created

UdpHandler::getSocket()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 2
b 0
f 0
nc 3
nop 0
dl 0
loc 9
ccs 0
cts 6
cp 0
crap 12
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\VarDumper\Handler;
6
7
use Exception;
8
use RuntimeException;
9
use Socket;
10
use Yiisoft\VarDumper\HandlerInterface;
11
12
final class UdpHandler implements HandlerInterface
13
{
14
    private ?Socket $socket = null;
15
16
    public function __construct(
17
        private string $host = '127.0.0.1',
18
        private int $port = 8890,
19
    ) {
20
        if (!extension_loaded('sockets')) {
21
            throw new Exception('The "ext-socket" extension is not installed.');
22
        }
23
    }
24
25
    /**
26
     * Sends encode with {@see \json_encode()} function $variable to a UDP socket.
27
     */
28
    public function handle(mixed $variable, int $depth, bool $highlight = false): void
29
    {
30
        $socket = $this->getSocket();
31
32
        $data = json_encode($variable);
33
        if (!socket_sendto($socket, $data, strlen($data), 0, $this->host, $this->port)) {
34
            throw new RuntimeException(
35
                sprintf(
36
                    'Could not send a dump to %s:%d',
37
                    $this->host,
38
                    $this->port,
39
                )
40
            );
41
        }
42
    }
43
44
    /**
45
     * @throws RuntimeException When a connection cannot be opened.
46
     */
47
    private function getSocket(): Socket
48
    {
49
        if ($this->socket === null) {
50
            $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
51
            if (!$this->socket) {
52
                throw new RuntimeException('Cannot create a UDP socket connection.');
53
            }
54
        }
55
        return $this->socket;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->socket could return the type null which is incompatible with the type-hinted return Socket. Consider adding an additional type-check to rule them out.
Loading history...
56
    }
57
}
58