PatternMiddleware::__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 PatternMiddleware implements MiddlewareInterface
13
{
14
    protected $patterns = [];
15
16 3
    public function __construct(array $patterns = [])
17
    {
18 3
        foreach ($patterns as $pattern => $middleware)
19
        {
20 2
            $this->register($pattern, $middleware);
21
        }
22 3
    }
23
24 3
    public function register(string $pattern, MiddlewareInterface $middleware): self
25
    {
26 3
        $this->patterns[$pattern] = $middleware;
27 3
        return $this;
28
    }
29
30 2
    public function process(ServerRequestInterface $req, RequestHandlerInterface $handler): ResponseInterface
31
    {
32 2
        $path = $req->getUri()->getPath();
33
34 2
        foreach ($this->patterns as $pattern => $middleware)
35
        {
36 2
            $matches = [];
37 2
            if (preg_match('#^' . $pattern . '$#', $path, $matches))
38
            {
39 1
                foreach ($matches as $key => $value)
40
                {
41 1
                    if (is_string($key))
42
                    {
43 1
                        $req = $req->withAttribute($key, $value);
44
                    }
45
                }
46
47 2
                return $middleware->process($req, $handler);
48
            }
49
        }
50
51 1
        return $handler->handle($req);
52
    }
53
}