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

UdpHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 17
c 2
b 0
f 0
dl 0
loc 44
ccs 0
cts 20
cp 0
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A handle() 0 11 2
A getSocket() 0 9 3
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