Passed
Push — master ( b6a195...1e79f7 )
by mcfog
03:21
created

CatchMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lit\Nimo\Middlewares;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Server\MiddlewareInterface;
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 1
    public function __construct($innerMiddleware, callable $catcher, string $catchClass = \Throwable::class)
22
    {
23 1
        parent::__construct($innerMiddleware);
24 1
        $this->catchClass = $catchClass;
25 1
        $this->catcher = $catcher;
26 1
    }
27
28 1
    public static function catcher(callable $catcher, string $catchClass = \Throwable::class): MiddlewareInterface
29
    {
30 1
        return NoopMiddleware::instance()->catch($catcher, $catchClass);
31
    }
32
33 1
    protected function main(): ResponseInterface
34
    {
35
        try {
36 1
            return $this->innerMiddleware->process($this->request, $this->handler);
37 1
        } catch (\Throwable $e) {
38 1
            if ($e instanceof $this->catchClass) {
39 1
                return ($this->catcher)($e, $this->request, $this->handler, $this->innerMiddleware);
40
            }
41
            throw $e;
42
        }
43
    }
44
}
45