Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
ExceptionContextExtender
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
3 / 3
6
100.00% covered (success)
100.00%
1 / 1
 extend
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 buildLogMessage
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 createMessage
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; under version 2
7 * of the License (non-upgradable).
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 *
18 * Copyright (c) 2021 (original work) Open Assessment Technologies SA
19 */
20
21declare(strict_types=1);
22
23namespace oat\oatbox\log\logger\extender;
24
25use Throwable;
26
27class ExceptionContextExtender implements ContextExtenderInterface
28{
29    public function extend(array $context): array
30    {
31        if (isset($context[self::CONTEXT_EXCEPTION]) && $context[self::CONTEXT_EXCEPTION] instanceof Throwable) {
32            $context[self::CONTEXT_EXCEPTION] = $this->buildLogMessage($context[self::CONTEXT_EXCEPTION]);
33        }
34
35        return $context;
36    }
37
38    private function buildLogMessage(Throwable $exception): string
39    {
40        $message = $this->createMessage($exception);
41
42        if ($exception->getPrevious()) {
43            $message = sprintf(
44                '%s, previous: %s',
45                $message,
46                $this->buildLogMessage($exception->getPrevious())
47            );
48        }
49
50        return $message;
51    }
52
53    private function createMessage(Throwable $exception): string
54    {
55        return sprintf(
56            '"%s", code: %s, file: "%s", line: %s',
57            $exception->getMessage(),
58            $exception->getCode(),
59            $exception->getFile(),
60            $exception->getLine()
61        );
62    }
63}