1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\VarDumper\Handler; |
6
|
|
|
|
7
|
|
|
use RuntimeException; |
8
|
|
|
use Yiisoft\VarDumper\HandlerInterface; |
9
|
|
|
|
10
|
|
|
final class StreamHandler implements HandlerInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var callable |
14
|
|
|
*/ |
15
|
|
|
private $encoder; |
16
|
|
|
/** |
17
|
|
|
* @var null|resource |
18
|
|
|
*/ |
19
|
|
|
private $stream = null; |
20
|
|
|
|
21
|
10 |
|
public function __construct( |
22
|
|
|
private $uri = 'udp://127.0.0.1:8890' |
23
|
|
|
) { |
24
|
10 |
|
if (!is_string($this->uri) && !is_resource($this->uri)) { |
|
|
|
|
25
|
|
|
throw new \InvalidArgumentException( |
26
|
|
|
sprintf( |
27
|
|
|
'Argument $uri must be a string or a resource, "%s" given.', |
28
|
|
|
gettype($this->uri) |
29
|
|
|
) |
30
|
|
|
); |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Sends encode with {@see \json_encode()} function $variable to a UDP socket. |
36
|
|
|
*/ |
37
|
10 |
|
public function handle(mixed $variable, int $depth, bool $highlight = false): void |
38
|
|
|
{ |
39
|
10 |
|
$data = ($this->encoder ?? 'json_encode')($variable); |
40
|
10 |
|
if (!is_string($data)) { |
41
|
|
|
throw new RuntimeException( |
42
|
|
|
sprintf( |
43
|
|
|
'Encoder must return a string, %s returned.', |
44
|
|
|
gettype($data) |
45
|
|
|
) |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
10 |
|
$this->initializeStream(); |
50
|
|
|
|
51
|
10 |
|
if (!$this->writeToStream($data)) { |
52
|
|
|
$this->initializeStream(); |
53
|
|
|
|
54
|
|
|
$this->writeToStream($data); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
public function withEncoder(callable $encoder): HandlerInterface |
59
|
|
|
{ |
60
|
2 |
|
$new = clone $this; |
61
|
2 |
|
$new->encoder = $encoder; |
62
|
2 |
|
return $new; |
63
|
|
|
} |
64
|
|
|
|
65
|
10 |
|
private function initializeStream(): void |
66
|
|
|
{ |
67
|
10 |
|
if (is_string($this->uri)) { |
|
|
|
|
68
|
1 |
|
$this->stream = fsockopen($this->uri); |
69
|
|
|
} else { |
70
|
9 |
|
$this->stream = $this->uri; |
|
|
|
|
71
|
|
|
} |
72
|
|
|
|
73
|
10 |
|
if (!is_resource($this->stream)) { |
|
|
|
|
74
|
1 |
|
throw new RuntimeException('Cannot initialize a stream.'); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
10 |
|
private function writeToStream(bool|string $data): bool |
79
|
|
|
{ |
80
|
10 |
|
return @fwrite($this->stream, $data) !== false; |
|
|
|
|
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|