ExceptionLoggerMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\Logger\Application\Http\Middleware;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Psr\Log\LoggerInterface;
12
use Throwable;
13
use function get_class;
14
use function json_encode;
15
use function sprintf;
16
17
class ExceptionLoggerMiddleware implements MiddlewareInterface
18
{
19
    private const UNEXPECTED_EXCEPTION_MESSAGE = 'Unexpected error occurred during %s exception message serialization.';
20
    private LoggerInterface $logger;
21
22 2
    public function __construct(LoggerInterface $logger)
23
    {
24 2
        $this->logger = $logger;
25 2
    }
26
27 2
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
28
    {
29
        try {
30 2
            return $handler->handle($request);
31 1
        } catch (Throwable $exception) {
32 1
            $message = json_encode([
33 1
                'message' => $exception->getMessage(),
34 1
                'code' => $exception->getCode(),
35 1
                'file' => $exception->getFile(),
36 1
                'line' => $exception->getLine()
37
            ]);
38 1
            $this->logger->error(
39 1
                $message
40 1
                    ? $message
41 1
                    : sprintf(self::UNEXPECTED_EXCEPTION_MESSAGE, get_class($exception))
42
            );
43
44 1
            throw $exception;
45
        }
46
    }
47
}
48