Passed
Push — develop ( 24796a...8e17d9 )
by nguereza
02:10
created

AbstractFormatter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
rs 10
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   http://www.iacademy.cf
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
     * The configuration to use
69
     * @var Configuration
70
     */
71
    protected Configuration $config;
72
    
73
    /**
74
     * Create new instance
75
     * @param Configuration $config the configuration to use
76
     */
77
    public function __construct(Configuration $config) {
78
        $this->config = $config;
79
    }
80
81
    /**
82
     * Get Exception information data
83
     * @param  Throwable $exception
84
     * @return array<string, mixed>        the exception data
85
     */
86
    protected function getExceptionData(Throwable $exception): array
87
    {
88
        $data = [
89
            'message' => $exception->getMessage(),
90
            'code' => $exception->getCode(),
91
            'file' => $exception->getFile(),
92
            'line' => $exception->getLine()
93
        ];
94
95
        $traces = $exception->getTrace();
96
        $traceStr = "\n";
97
        foreach ($traces as $i => $trace) {
98
            $traceStr .= sprintf(
99
                '%d. %s:%s%s%s(%s)::%d',
100
                $i + 1,
101
                $trace['file'] ?? '',
102
                $trace['class'] ?? '',
103
                $trace['type'] ?? '',
104
                $trace['function'] ?? '',
105
                isset($trace['args']) ? '...' : '',
106
                $trace['line'] ?? ''
107
            ) . "\n";
108
        }
109
110
        $data['trace'] = $traceStr;
111
112
        return $data;
113
    }
114
115
    /**
116
     * Interpolates context values into the message placeholders.
117
     * @param  string $message
118
     * @param  array<string, mixed>  $context
119
     * @return string
120
     */
121
    protected function interpolate(string $message, array $context): string
122
    {
123
        if (strpos($message, '{') === false) {
124
            return $message;
125
        }
126
127
        $replacements = [];
128
        foreach ($context as $key => $value) {
129
            $replacements['{' . $key . '}'] = Str::stringify($value);
130
        }
131
132
        return strtr($message, $replacements);
133
    }
134
135
    /**
136
     * Get the current time for logging
137
     * Format: YYYY-mm-dd HH:ii:ss.uuuuuu
138
     * Microsecond precision for PHP 7.1 and greater
139
     *
140
     * @return string
141
     */
142
    protected function getLogTime(): string
143
    {
144
        $format = 'Y-m-d H:i:s.u';
145
        $useTimestamp = $this->config->get('timestamp', false);
0 ignored issues
show
Unused Code introduced by
The call to Platine\Stdlib\Config\AbstractConfiguration::get() has too many arguments starting with false. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

145
        /** @scrutinizer ignore-call */ 
146
        $useTimestamp = $this->config->get('timestamp', false);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
146
        if($useTimestamp === false){
0 ignored issues
show
Coding Style introduced by
Expected 1 space(s) after IF keyword; 0 found
Loading history...
147
            $format = 'H:i:s.u';
148
        }
149
        
150
        return (new DateTimeImmutable('now'))->format($format);
151
    }
152
}
153