MiddlewareManager   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 42
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A push() 0 6 1
A __invoke() 0 21 4
1
<?php
2
3
namespace PTS\Middleware;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
8
class MiddlewareManager
9
{
10
    /** @var callable[]|MiddlewareInterface[] */
11
    protected $middlewares = [];
12
    /** @var array|callable[] */
13
    protected $exceptionHandlers = [];
14
15 6
    public function push(callable $middleware, callable $exceptionHandler = null): self
16
    {
17 6
        $this->middlewares[] = $middleware;
18 6
        $this->exceptionHandlers[] = $exceptionHandler;
19 6
        return $this;
20
    }
21
22
    /**
23
     * @param ServerRequestInterface $request
24
     * @return mixed|null|ResponseInterface
25
     *
26
     * @throws \Throwable
27
     */
28 7
    public function __invoke(ServerRequestInterface $request)
29
    {
30 7
        if (empty($this->middlewares)) {
31 2
            return null;
32
        }
33
34 6
        $middleware = array_shift($this->middlewares);
35 6
        $exceptionHandler = array_shift($this->exceptionHandlers);
36
37
        try {
38 6
            $response = $middleware($request, $this);
39 2
        } catch (\Throwable $exception) {
40 2
            if ($exceptionHandler === null) {
41 1
                throw $exception;
42
            }
43
44 1
            $response = $exceptionHandler($exception);
45
        }
46
47 5
        return $response;
48
    }
49
}
50