Issues (3)

src/Emitter.php (1 issue)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace RazonYang\Psr7\Swoole;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\StreamInterface;
9
use Swoole\Http\Response;
10
11
final class Emitter implements EmitterInterface
12
{
13
    public function __construct(
14
        private Response $response,
15
        private int $bufferSize = 8_388_608, // 8MB
0 ignored issues
show
The constant RazonYang\Psr7\Swoole\8_388_608 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
16
    ) {
17
    }
18
19
    public function withBufferSize(int $size)
20
    {
21
        $new = clone $this;
22
        $new->bufferSize = $size;
23
24
        return $new;
25
    }
26
27
    public function getBufferSize(): int
28
    {
29
        return $this->bufferSize;
30
    }
31
32
    public function emit(ResponseInterface $response, bool $withoutBody = false)
33
    {
34
        $this->response->status($response->getStatusCode(), $response->getReasonPhrase());
35
36
        foreach ($response->getHeaders() as $key => $value) {
37
            $this->response->header($key, $value);
38
        }
39
40
        if (!$withoutBody) {
41
            $this->emitBody($response->getBody());
42
        }
43
44
        $this->response->end();
45
    }
46
47
    private function emitBody(StreamInterface $body): void
48
    {
49
        if ($body->isSeekable()) {
50
            $body->rewind();
51
        }
52
53
        while (!$body->eof()) {
54
            $this->response->write($body->read($this->bufferSize));
55
        }
56
    }
57
}
58