Passed
Push — master ( c50645...4f2252 )
by Koldo
02:16
created

ErrorMiddleware::setErrorHandler()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3.6875

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
ccs 1
cts 4
cp 0.25
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 0
crap 3.6875
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\Application\Http\Middleware;
6
7
use ErrorException;
8
use Franzl\Middleware\Whoops\WhoopsMiddleware;
9
use Franzl\Middleware\Whoops\WhoopsRunner;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Psr\Http\Server\MiddlewareInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
use Throwable;
15
use Zend\Diactoros\Response\TextResponse;
16
17
use function class_exists;
18
use function error_reporting;
19
use function restore_error_handler;
20
use function set_error_handler;
21
22
class ErrorMiddleware implements MiddlewareInterface
23
{
24
    /** @var bool */
25
    private $debug;
26
27 4
    public function __construct(bool $debug)
28
    {
29 4
        $this->debug = $debug;
30 4
    }
31
32 4
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
33
    {
34 4
        $this->setErrorHandler();
35
36
        try {
37 4
            if ($this->debug && class_exists(WhoopsMiddleware::class)) {
38 2
                $whoopsMiddleware = new WhoopsMiddleware();
39 2
                return $whoopsMiddleware->process($request, $handler);
40
            }
41
42 2
            $response = $handler->handle($request);
43 1
            return $response;
44 1
        } catch (Throwable $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
45
        }
46
47 1
        return $this->getErrorResponse($e, $request);
48
    }
49
50 4
    private function setErrorHandler(): void
51
    {
52
        set_error_handler(static function ($errno, $errstr, $errfile, $errline) {
53
            if (! (error_reporting() & $errno)) {
54
                // Error is not in mask
55
                return;
56
            }
57
            throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
58 4
        });
59 4
    }
60
61 1
    private function getErrorResponse(Throwable $e, ServerRequestInterface $request): ResponseInterface
62
    {
63 1
        restore_error_handler();
64
65 1
        if ($this->debug && class_exists(WhoopsRunner::class)) {
66
            $whoops = new WhoopsRunner();
67
            return $whoops->handle($e, $request);
68
        }
69
70 1
        return new TextResponse('Unexpected Server Error Occurred', 500);
71
    }
72
}
73