CatchMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
wmc 5
eloc 13
c 0
b 0
f 0
dl 0
loc 37
ccs 12
cts 13
cp 0.9231
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A catcher() 0 5 1
A main() 0 9 3
A __construct() 0 8 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