CatchMiddleware::catcher()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 5
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lit\Nimo\Middlewares;
6
7
use Lit\Nimo\Interfaces\ExceptionHandlerInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
11
/**
12
 * Middleware wrapper that try to catch soem exception when running inner middleware.
13
 */
14
class CatchMiddleware extends AbstractWrapperMiddleware
15
{
16
    /**
17
     * @var string
18
     */
19
    protected $catchClass;
20
    /**
21
     * @var ExceptionHandlerInterface
22
     */
23
    protected $catcher;
24
25 1
    public function __construct(
26
        $innerMiddleware,
27
        ExceptionHandlerInterface $catcher,
28
        string $catchClass = \Throwable::class
29
    ) {
30 1
        parent::__construct($innerMiddleware);
31 1
        $this->catchClass = $catchClass;
32 1
        $this->catcher = $catcher;
33 1
    }
34
35 1
    public static function catcher(
36
        ExceptionHandlerInterface $catcher,
37
        string $catchClass = \Throwable::class
38
    ): MiddlewareInterface {
39 1
        return NoopMiddleware::instance()->catch($catcher, $catchClass);
40
    }
41
42 1
    protected function main(): ResponseInterface
43
    {
44
        try {
45 1
            return $this->innerMiddleware->process($this->request, $this->handler);
46 1
        } catch (\Throwable $e) {
47 1
            if ($e instanceof $this->catchClass) {
48 1
                return $this->catcher->handle($e, $this->request, $this->handler, $this->innerMiddleware);
49
            }
50
            throw $e;
51
        }
52
    }
53
}
54