MethodMiddleware::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Aidphp\Routing\Middleware;
6
7
use Psr\Http\Server\MiddlewareInterface;
8
use Psr\Http\Server\RequestHandlerInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
12
class MethodMiddleware implements MiddlewareInterface
13
{
14
    protected $methods = [];
15
16 3
    public function __construct(array $methods = [])
17
    {
18 3
        foreach ($methods as $method => $middleware)
19
        {
20 2
            $this->register($method, $middleware);
21
        }
22 3
    }
23
24 3
    public function register(string $method, MiddlewareInterface $middleware): self
25
    {
26 3
        $this->methods[$method] = $middleware;
27 3
        return $this;
28
    }
29
30 2
    public function process(ServerRequestInterface $req, RequestHandlerInterface $handler): ResponseInterface
31
    {
32 2
        $method = $req->getMethod();
33
34 2
        if (isset($this->methods[$method]))
35
        {
36 1
            return ($this->methods[$method])->process($req, $handler);
37
        }
38
39 1
        $req = $req->withAttribute(self::class, array_keys($this->methods));
40
41 1
        return $handler->handle($req);
42
    }
43
}