ServerRequestRunner   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 5
eloc 12
c 3
b 0
f 0
dl 0
loc 53
ccs 14
cts 14
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isResponseWithoutBody() 0 3 2
A run() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace HttpSoft\Runner;
6
7
use HttpSoft\Emitter\EmitterInterface;
8
use HttpSoft\Emitter\SapiEmitter;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
12
use function in_array;
13
use function strtoupper;
14
15
final class ServerRequestRunner
16
{
17
    /**
18
     * Response status codes for which the response body is not sent.
19
     */
20
    private const NO_BODY_RESPONSE_CODES = [100, 101, 102, 204, 205, 304];
21
22
    /**
23
     * @var MiddlewarePipelineInterface
24
     */
25
    private MiddlewarePipelineInterface $pipeline;
26
27
    /**
28
     * @var EmitterInterface
29
     */
30
    private EmitterInterface $emitter;
31
32
    /**
33
     * @param MiddlewarePipelineInterface|null $pipeline
34
     * @param EmitterInterface|null $emitter
35
     */
36 4
    public function __construct(?MiddlewarePipelineInterface $pipeline = null, ?EmitterInterface $emitter = null)
37
    {
38 4
        $this->pipeline = $pipeline ?? new MiddlewarePipeline();
39 4
        $this->emitter = $emitter ?? new SapiEmitter();
40
    }
41
42
    /**
43
     * @param ServerRequestInterface $request
44
     * @param RequestHandlerInterface|null $defaultHandler
45
     * @psalm-suppress RedundantCast
46
     */
47 4
    public function run(ServerRequestInterface $request, ?RequestHandlerInterface $defaultHandler = null): void
48
    {
49 4
        $response = ($defaultHandler === null)
50 1
            ? $this->pipeline->handle($request)
51 3
            : $this->pipeline->process($request, $defaultHandler)
52 4
        ;
53
54 3
        $this->emitter->emit($response, $this->isResponseWithoutBody(
55 3
            (string) $request->getMethod(),
56 3
            (int) $response->getStatusCode(),
57 3
        ));
58
    }
59
60
    /**
61
     * @param string $requestMethod
62
     * @param int $responseCode
63
     * @return bool
64
     */
65 3
    private function isResponseWithoutBody(string $requestMethod, int $responseCode): bool
66
    {
67 3
        return (strtoupper($requestMethod) === 'HEAD' || in_array($responseCode, self::NO_BODY_RESPONSE_CODES, true));
68
    }
69
}
70