Passed
Pull Request — master (#125)
by Dmitriy
12:55
created

ServerSentEventsStream::eof()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
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
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting ',' or ')' on line 96 at column 28
Loading history...
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