Test Failed
Branch master (e46a7e)
by mcfog
02:27
created

CatchMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 35
ccs 0
cts 21
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A catcher() 0 4 1
A main() 0 11 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lit\Nimo\Middlewares;
6
7
use Interop\Http\Server\MiddlewareInterface;
8
use Psr\Http\Message\ResponseInterface;
9
10
class CatchMiddleware extends AbstractWrapperMiddleware
11
{
12
    /**
13
     * @var string
14
     */
15
    protected $catchClass;
16
    /**
17
     * @var callable
18
     */
19
    protected $catcher;
20
21
    public function __construct($innerMiddleware, callable $catcher, string $catchClass = \Throwable::class)
22
    {
23
        parent::__construct($innerMiddleware);
24
        $this->catchClass = $catchClass;
25
        $this->catcher = $catcher;
26
    }
27
28
    public static function catcher(callable $catcher, string $catchClass = \Throwable::class): MiddlewareInterface
29
    {
30
        return NoopMiddleware::instance()->catch($catcher, $catchClass);
31
    }
32
33
    protected function main(): ResponseInterface
34
    {
35
        try {
36
            return $this->innerMiddleware->process($this->request, $this->handler);
37
        } catch (\Throwable $e) {
38
            if ($e instanceof $this->catchClass) {
39
                return ($this->catcher)($e, $this->request, $this->handler);
40
            }
41
            throw $e;
42
        }
43
    }
44
}
45