Passed
Pull Request — master (#95)
by Dmitriy
03:40
created

UdpHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 36
ccs 0
cts 13
cp 0
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A handle() 0 6 1
A getSocket() 0 9 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\VarDumper\Handler;
6
7
use Socket;
8
use Yiisoft\VarDumper\HandlerInterface;
9
10
final class UdpHandler implements HandlerInterface
11
{
12
    private ?Socket $socket = null;
13
14
    public function __construct(
15
        private string $host = '127.0.0.1',
16
        private int $port = 8890,
17
    ) {
18
        if (!extension_loaded('sockets')) {
19
            throw new \Exception('The "ext-socket" extension is not installed.');
20
        }
21
    }
22
23
    /**
24
     * Sends encode with {@see \json_encode()} function $variable to a UDP socket.
25
     */
26
    public function handle(mixed $variable, int $depth, bool $highlight = false): void
27
    {
28
        $socket = $this->getSocket();
29
30
        $data = json_encode($variable);
31
        socket_sendto($socket, $data, strlen($data), 0, $this->host, $this->port);
32
    }
33
34
    /**
35
     * @throws RuntimeException When a connection cannot be opened.
36
     */
37
    private function getSocket(): Socket
38
    {
39
        if ($this->socket === null) {
40
            $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
41
            if (!$this->socket) {
42
                throw new \RuntimeException('Cannot create a UDP socket connection.');
43
            }
44
        }
45
        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...
46
    }
47
}
48