PrefixMiddleware   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 37
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A register() 0 5 1
A process() 0 18 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
}