AbstractFormatter::getExceptionData()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 27
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 20
nc 2
nop 1
dl 0
loc 27
rs 9.6
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Platine Logger
5
 *
6
 * Platine Logger is the implementation of PSR 3
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Logger
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a copy
13
 * of this software and associated documentation files (the "Software"), to deal
14
 * in the Software without restriction, including without limitation the rights
15
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the Software is
17
 * furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
 * SOFTWARE.
29
 */
30
31
/**
32
 *  @file AbstractFormatter.php
33
 *
34
 *  The base logger formatter class
35
 *
36
 *  @package    Platine\Logger\Formatter
37
 *  @author Platine Developers Team
38
 *  @copyright  Copyright (c) 2020
39
 *  @license    http://opensource.org/licenses/MIT  MIT License
40
 *  @link   https://www.platine-php.com
41
 *  @version 1.0.0
42
 *  @filesource
43
 */
44
45
declare(strict_types=1);
46
47
namespace Platine\Logger\Formatter;
48
49
use DateTimeImmutable;
50
use Platine\Logger\Configuration;
51
use Platine\Logger\LoggerFormatterInterface;
52
use Platine\Stdlib\Helper\Str;
53
use Throwable;
54
55
/**
56
 * @class AbstractFormatter
57
 * @package Platine\Logger\Formatter
58
 */
59
abstract class AbstractFormatter implements LoggerFormatterInterface
60
{
61
    /**
62
     * Log fields separated by tabs to form a TSV (CSV with tabs).
63
     * @var string
64
     */
65
    protected string $tab = "\t";
66
67
    /**
68
     * Create new instance
69
     * @param Configuration $config the configuration to use
70
     */
71
    public function __construct(protected Configuration $config)
72
    {
73
    }
74
75
    /**
76
     * Get Exception information data
77
     * @param  Throwable $exception
78
     * @return array<string, mixed> the exception data
79
     */
80
    protected function getExceptionData(Throwable $exception): array
81
    {
82
        $data = [
83
            'message' => $exception->getMessage(),
84
            'code' => $exception->getCode(),
85
            'file' => $exception->getFile(),
86
            'line' => $exception->getLine()
87
        ];
88
89
        $traces = $exception->getTrace();
90
        $traceStr = "\n";
91
        foreach ($traces as $i => $trace) {
92
            $traceStr .= sprintf(
93
                '%d. %s:%s%s%s(%s)::%d',
94
                $i + 1,
95
                $trace['file'] ?? '',
96
                $trace['class'] ?? '',
97
                $trace['type'] ?? '',
98
                $trace['function'],
99
                isset($trace['args']) ? '...' : '',
100
                $trace['line'] ?? ''
101
            ) . "\n";
102
        }
103
104
        $data['trace'] = $traceStr;
105
106
        return $data;
107
    }
108
109
    /**
110
     * Interpolates context values into the message placeholders.
111
     * @param  string $message
112
     * @param  array<string, mixed>  $context
113
     * @return string
114
     */
115
    protected function interpolate(string $message, array $context): string
116
    {
117
        if (strpos($message, '{') === false) {
118
            return $message;
119
        }
120
121
        $replacements = [];
122
        foreach ($context as $key => $value) {
123
            $replacements['{' . $key . '}'] = Str::stringify($value);
124
        }
125
126
        return strtr($message, $replacements);
127
    }
128
129
    /**
130
     * Get the current time for logging
131
     * Format: YYYY-mm-dd HH:ii:ss.uuuuuu
132
     * Microsecond precision for PHP 7.1 and greater
133
     *
134
     * @return string
135
     */
136
    protected function getLogTime(): string
137
    {
138
        $format = 'Y-m-d H:i:s.u';
139
        $useTimestamp = $this->config->get('timestamp');
140
        if ($useTimestamp === false) {
141
            $format = 'H:i:s.u';
142
        }
143
144
        return (new DateTimeImmutable('now'))->format($format);
145
    }
146
}
147