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