Passed
Push — master ( 3e03bc...37eb29 )
by Felipe
01:50
created

StatusCodeHandler   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 44
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 2
A handle() 0 4 1
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of coisa/http.
4
 *
5
 * (c) Felipe Sayão Lobato Abreu <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace CoiSA\Http\Handler;
12
13
use Fig\Http\Message\StatusCodeInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\ServerRequestInterface;
16
use Psr\Http\Server\RequestHandlerInterface;
17
18
/**
19
 * Class StatusCodeHandler
20
 *
21
 * @package CoiSA\Http\Handler
22
 */
23
final class StatusCodeHandler implements RequestHandlerInterface
24
{
25
    /**
26
     * @var RequestHandlerInterface
27
     */
28
    private $handler;
29
30
    /**
31
     * @var int
32
     */
33
    private $statusCode;
34
35
    /**
36
     * StatusCodeHandler constructor.
37
     *
38
     * @param RequestHandlerInterface $requestHandler
39
     * @param int                     $statusCode
40
     *
41
     * @throws \ReflectionException
42
     */
43
    public function __construct(
44
        RequestHandlerInterface $requestHandler,
45
        int $statusCode
46
    ) {
47
        $this->handler    = $requestHandler;
48
        $this->statusCode = $statusCode;
49
50
        $reflection    = new \ReflectionClass(StatusCodeInterface::class);
51
        $allowedStatus = $reflection->getConstants();
52
53
        if (!\in_array($this->statusCode, $allowedStatus)) {
54
            throw new \UnexpectedValueException('Invalid HTTP Status Code');
55
        }
56
    }
57
58
    /**
59
     * @param ServerRequestInterface $request
60
     *
61
     * @return ResponseInterface
62
     */
63
    public function handle(ServerRequestInterface $request): ResponseInterface
64
    {
65
        return $this->handler->handle($request)
66
            ->withStatus($this->statusCode);
67
    }
68
}
69