ExceptionHandler::format()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 21
rs 9.8666
1
<?php
2
3
namespace Tleckie\Log\Formatter\Handler;
4
5
use Exception;
6
use Throwable;
7
8
/**
9
 * Class ExceptionHandler
10
 *
11
 * @package Tleckie\Log\Formatter\Handler
12
 * @author  Teodoro Leckie Westberg <[email protected]>
13
 */
14
class ExceptionHandler extends Handler
15
{
16
    /**
17
     * @param mixed $message
18
     * @param array $context
19
     * @return string
20
     */
21
    public function handler(mixed $message, array $context = []): string
22
    {
23
        if ($message instanceof Exception) {
24
            $msg = $this->encode($this->clearEof($message->getMessage()));
25
            $exception = $this->encode($this->format($message));
26
27
            return sprintf('%s %s', $msg, $exception);
28
        }
29
30
        return parent::handler($message, $context);
31
    }
32
33
    /**
34
     * @param Throwable $exception
35
     * @return array
36
     */
37
    private function format(Throwable $exception): array
38
    {
39
        $data = [
40
            'class' => get_class($exception),
41
            'message' => $this->clearEof($exception->getMessage()),
42
            'code' => $exception->getCode(),
43
            'file' => sprintf("%s:%s", $exception->getFile(), $exception->getLine())
44
        ];
45
46
        $trace = $exception->getTrace();
47
        foreach ($trace as $frame) {
48
            if (isset($frame['file'])) {
49
                $data['trace'][] = sprintf("%s:%s", $frame['file'], $frame['line']);
50
            }
51
        }
52
53
        if ($previous = $exception->getPrevious()) {
54
            $data['previous'] = $this->format($previous);
55
        }
56
57
        return $data;
58
    }
59
}
60