1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Debug\Api; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Psr\Http\Message\StreamInterface; |
9
|
|
|
|
10
|
|
|
final class ServerSentEventsStream implements StreamInterface, \Stringable |
11
|
|
|
{ |
12
|
|
|
public array $buffer = []; |
13
|
|
|
private bool $eof = false; |
14
|
|
|
|
15
|
|
|
public function __construct( |
16
|
|
|
private Closure $stream, |
17
|
|
|
) { |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public function close(): void |
21
|
|
|
{ |
22
|
|
|
$this->eof = true; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function detach(): void |
26
|
|
|
{ |
27
|
|
|
$this->eof = true; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function getSize() |
31
|
|
|
{ |
32
|
|
|
return null; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function tell(): int |
36
|
|
|
{ |
37
|
|
|
return 0; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function eof(): bool |
41
|
|
|
{ |
42
|
|
|
return $this->eof; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function isSeekable(): bool |
46
|
|
|
{ |
47
|
|
|
return false; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function seek($offset, $whence = SEEK_SET): void |
51
|
|
|
{ |
52
|
|
|
throw new \RuntimeException('Stream is not seekable'); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function rewind(): void |
56
|
|
|
{ |
57
|
|
|
throw new \RuntimeException('Stream is not seekable'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function isWritable(): bool |
61
|
|
|
{ |
62
|
|
|
return false; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function write($string): void |
66
|
|
|
{ |
67
|
|
|
throw new \RuntimeException('Stream is not writable'); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function isReadable(): bool |
71
|
|
|
{ |
72
|
|
|
return true; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* TODO: support length reading |
77
|
|
|
*/ |
78
|
|
|
public function read(int $length): string |
79
|
|
|
{ |
80
|
|
|
$continue = ($this->stream)($this->buffer); |
81
|
|
|
|
82
|
|
|
if (!$continue) { |
83
|
|
|
$this->eof = true; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
$output = ''; |
87
|
|
|
foreach ($this->buffer as $key => $value) { |
88
|
|
|
unset($this->buffer[$key]); |
89
|
|
|
$output .= sprintf("data: %s\n", $value); |
90
|
|
|
} |
91
|
|
|
$output .= "\n"; |
92
|
|
|
return $output; |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
public function getContents(): string |
96
|
|
|
{ |
97
|
|
|
return $this->read(1024); |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
public function getMetadata($key = null): array |
101
|
|
|
{ |
102
|
|
|
return []; |
103
|
|
|
} |
104
|
|
|
|
105
|
|
|
public function __toString(): string |
106
|
|
|
{ |
107
|
|
|
return $this->getContents(); |
108
|
|
|
} |
109
|
|
|
} |
110
|
|
|
|