Passed
Push — feature_AddTestsAndReduceCodeC... ( a4bd39...0c72e4 )
by Markus
02:06
created

SeqCompactJsonFormatter::getExtractContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Msschl\Monolog\Formatter;
4
5
use DateTime;
6
use Monolog\Formatter\FormatterInterface;
7
use Monolog\Formatter\JsonFormatter;
8
use Throwable;
9
10
/**
11
 * This file is part of the msschl\monolog-seq-handler package.
12
 *
13
 * Copyright (c) 2018 Markus Schlotbohm
14
 *
15
 * For the full copyright and license information, please view the LICENSE.md
16
 * file that was distributed with this source code.
17
 */
18
class SeqCompactJsonFormatter extends SeqBaseFormatter
19
{
20
21
    /**
22
     * The extract context flag.
23
     * Whether to extract the context array to the root or not.
24
     *
25
     * @var bool
26
     */
27
    protected $extractContext;
28
29
    /**
30
     * The extract extras flag.
31
     * Whether to extract the extras array to the root or not.
32
     *
33
     * @var bool
34
     */
35
    protected $extractExtras;
36
37
    /**
38
     * Initializes a new instance of the {@see SeqCompactJsonFormatter} class.
39
     *
40
     * @param  bool $extractContext Flag that indicates whether to extract the extras array
41
     *                              to the root or not.
42
     * @param  bool $extractExtras  Flag that indicates whether to extract the context array
43
     *                              to the root or not.
44
     */
45
	public function __construct(bool $extractContext = true, bool $extractExtras = true)
46
	{
47
        $this->appendNewline = false;
48
        $this->batchMode = JsonFormatter::BATCH_MODE_NEWLINES;
49
        $this->extractContext = $extractContext;
50
        $this->extractExtras = $extractExtras;
51
	}
52
53
    /**
54
     * Returns a string with the content type for the seq-formatter.
55
     *
56
     * @return string
57
     */
58
    public function getContentType() : string {
59
        return 'application/vnd.serilog.clef';
60
    }
61
62
    /**
63
     * Gets whether the flag extract content is set or not.
64
     *
65
     * @return bool
66
     */
67
    public function getExtractContent() : bool
68
    {
69
        return $this->extractContext;
70
    }
71
72
    /**
73
     * Sets the flag extract content.
74
     *
75
     * @param  bool $value The flag.
76
     * @return self
77
     */
78
    public function setExtractContent(bool $value)
79
    {
80
        $this->extractContext = $value;
81
82
        return $this;
83
    }
84
85
    /**
86
     * Gets whether the flag extract extras is set or not.
87
     *
88
     * @return bool
89
     */
90
    public function getExtractExtras()
91
    {
92
        return $this->extractExtras;
93
    }
94
95
    /**
96
     * Sets the flag extract extras.
97
     *
98
     * @param  bool $value The flag.
99
     * @return self
100
     */
101
    public function setExtractExtras(bool $value)
102
    {
103
        $this->extractExtras = $value;
104
105
        return $this;
106
    }
107
108
    /**
109
     * Normalizes given $data.
110
     *
111
     * @param mixed $data The data to normalize.
112
     * @return mixed
113
     */
114
    protected function normalize($data)
115
    {
116
        if (is_array($data) || $data instanceof \Traversable) {
117
            return $this->normalizeArray($data);
118
        }
119
120
        if ($data instanceof \Throwable) {
121
            return $this->normalizeException($data);
122
        }
123
124
        return $data;
125
    }
126
127
    private function normalizeArray($array)
128
    {
129
        $normalized = array();
130
131
        $count = 1;
132
        foreach ($array as $key => $value) {
133
            if ($count++ >= 1000) {
134
                $normalized['...'] = 'Over 1000 items, aborting normalization';
135
                break;
136
            }
137
138
            $normalized = $this->processLogRecord($normalized, $key, $value, $count);
139
        }
140
141
        return $normalized;
142
    }
143
144
    private function processLogRecord($array, $key, $value, /** @scrutinizer ignore-unused */ $count)
145
    {
146
        switch ($key) {
147
            case 'message':
148
                return $this->processMessage($array, $value);
149
150
            case 'datetime':
151
                return $this->processDateTime($array, $value);
152
153
            case 'level':
154
                $array['@l'] = $this->logLevelMap[$value];
155
                $array['LogLevelCode'] = $value;
156
                return $array;
157
            case 'level_name':
158
                return $array;
159
160
            case 'extra':
161
                return $this->processExtras($array, $value);
162
163
            case 'context':
164
                return $this->processContext($array, $value);
165
166
            default:
167
                $array[is_int($key) ? $key : SeqCompactJsonFormatter::ConvertSnakeCaseToPascalCase($key)] = $this->normalize($value);
168
                return $array;
169
        }
170
    }
171
172
    private function processMessage($array, $value)
173
    {
174
        $array['@m'] = $value;
175
        if (!(strpos($value, '{') === false)) {
176
            $array['@mt'] = $value;
177
        }
178
179
        return $array;
180
    }
181
182
    private function processDateTime($array, $value)
183
    {
184
        if ($value instanceof \DateTime) {
185
            $value = $value->format(DateTime::ISO8601);
186
        }
187
        $array['@t'] = $value;
188
189
        return $array;
190
    }
191
192
    private function processExtras($array, $value)
193
    {
194
        if (is_array($value) && is_array($normalizedArray = $this->normalize($value))) {
195
            if ($this->extractExtras) {
196
                $array = array_merge($normalizedArray, $array);
197
            } else {
198
                $array['Extra'] = $normalizedArray;
199
            }
200
        }
201
202
        return $array;
203
    }
204
205
    private function processContext($array, $value)
206
    {
207
        if (is_array($value)) {
208
            $exception = $this->extractException($value);
209
            $normalizedArray = $this->normalize($value);
210
211
            if (is_array($normalizedArray)) {
212
                if ($this->extractContext) {
213
                    $array = array_merge($normalizedArray, $array);
214
                } else {
215
                    $array['Context'] = $normalizedArray;
216
                }
217
            }
218
219
            if ($exception !== null) {
220
                if ($exception instanceof \Throwable) {
0 ignored issues
show
introduced by
$exception is always a sub-type of Throwable.
Loading history...
221
                    $exception = $this->normalizeException($exception);
222
                }
223
224
                $array['@x'] = $exception;
225
            }
226
        }
227
228
        return $array;
229
    }
230
}