Forward::sendResponse()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.5923

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 18
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 27
ccs 12
cts 18
cp 0.6667
crap 4.5923
rs 9.6666
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace WebPresentation;
6
7
use Throwable;
8
use WebPresentation\Exception\IOException;
9
use Psr\Http\Message\ResponseInterface as Response;
10
use Psr\Http\Message\ServerRequestInterface as ServerRequest;
11
12
class Forward
13
{
14
    private ServerRequest $request;
15
16
    private Response $response;
17
18 3
    public function __construct(ServerRequest $request, Response $response)
19
    {
20 3
        $this->request = $request;
21 3
        $this->response = $response;
22 3
    }
23
24 3
    public function sendResponse(string $target): Response
25
    {
26 3
        if (!\file_exists($target)) {
27
            throw new IOException(
28
                \sprintf("File `%s` does not exist.", $target)
29
            );
30
        }
31 3
        $level = \ob_get_level();
32 3
        \ob_start();
33 3
        \ob_implicit_flush(0);
34
        try {
35 3
            include $target;
36
        } catch (Throwable $e) {
37
            while (\ob_get_level() > $level) {
38
                \ob_end_clean();
39
            }
40
            throw $e;
41
        }
42
43 3
        $content = \ob_get_clean();
44
45 3
        $stream = $this->response->getBody();
46 3
        $stream->rewind();
47 3
        $stream->write($content);
48 3
        $this->response = $this->response->withBody($stream);
49
50 3
        return $this->response;
51
    }
52
}
53