PrefixMiddleware::process()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 9
cts 9
cp 1
rs 9.6666
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
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 PrefixMiddleware implements MiddlewareInterface
13
{
14
    protected $prefixes = [];
15
16 4
    public function __construct(array $prefixes = [])
17
    {
18 4
        foreach ($prefixes as $prefix => $middleware)
19
        {
20 3
            $this->register($prefix, $middleware);
21
        }
22 4
    }
23
24 4
    public function register(string $prefix, MiddlewareInterface $middleware): self
25
    {
26 4
        $this->prefixes[$prefix] = $middleware;
27 4
        return $this;
28
    }
29
30 3
    public function process(ServerRequestInterface $req, RequestHandlerInterface $handler): ResponseInterface
31
    {
32 3
        $uri  = $req->getUri();
33 3
        $path = $uri->getPath();
34
35 3
        foreach ($this->prefixes as $prefix => $middleware)
36
        {
37 3
            if (0 === strpos($path, $prefix))
38
            {
39 2
                $req = $req->withUri($uri->withPath(substr($path, strlen($prefix))))
40 2
                           ->withAttribute(self::class, $req->getAttribute(self::class, '') . $prefix);
41
42 3
                return $middleware->process($req, $handler);
43
            }
44
        }
45
46 1
        return $handler->handle($req);
47
    }
48
}