RequestMethodMiddleware::process()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 2
b 0
f 0
nc 2
nop 2
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
/**
4
 * This file is part of coisa/http.
5
 *
6
 * (c) Felipe Sayão Lobato Abreu <[email protected]>
7
 *
8
 * This source file is subject to the license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
declare(strict_types=1);
13
14
namespace CoiSA\Http\Middleware;
15
16
use Fig\Http\Message\RequestMethodInterface;
17
use Fig\Http\Message\StatusCodeInterface;
18
use Psr\Http\Message\ResponseInterface;
19
use Psr\Http\Message\ServerRequestInterface;
20
use Psr\Http\Server\MiddlewareInterface;
21
use Psr\Http\Server\RequestHandlerInterface;
22
23
/**
24
 * Class RequestMethodMiddleware
25
 *
26
 * @package CoiSA\Http\Middleware
27
 */
28
final class RequestMethodMiddleware implements MiddlewareInterface
29
{
30
    /**
31
     * @var string
32
     */
33
    private $method;
34
35
    /**
36
     * @var RequestHandlerInterface
37
     */
38
    private $handler;
39
40
    /**
41
     * @var MiddlewareInterface
42
     */
43
    private $middleware;
44
45
    /**
46
     * RequestMethodMiddleware constructor.
47
     *
48
     * @param string                  $method
49
     * @param RequestHandlerInterface $handler
50
     */
51 28
    public function __construct(string $method, RequestHandlerInterface $handler)
52
    {
53 28
        $constant = RequestMethodInterface::class . '::METHOD_' . \strtoupper($method);
54
55 28
        if (false === \defined($constant)) {
56 1
            throw new \UnexpectedValueException('Invalid HTTP method');
57
        }
58
59 28
        $this->method     = \constant($constant);
60 28
        $this->handler    = $handler;
61 28
        $this->middleware = new StatusCodeMiddleware(StatusCodeInterface::STATUS_METHOD_NOT_ALLOWED);
62 28
    }
63
64
    /**
65
     * @param ServerRequestInterface  $request
66
     * @param RequestHandlerInterface $handler
67
     *
68
     * @return ResponseInterface
69
     */
70 24
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
71
    {
72 24
        if ($this->method !== $request->getMethod()) {
73 11
            return $this->middleware->process($request, $handler);
74
        }
75
76 13
        return $this->handler->handle($request);
77
    }
78
}
79