Passed
Push — feature_AddTestsAndReduceCodeC... ( 966b75...692417 )
by Markus
02:09
created

SeqCompactJsonFormatter::processContext()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 10
nop 2
dl 0
loc 24
rs 8.5125
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 \Exception || $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
                $array = $this->processMessage($array, $value);
149
                break;
150
151
            case 'datetime':
152
                $array = $this->processDateTime($array, $value);
153
                break;
154
155
            case 'level':
156
                $array['@l'] = $this->logLevelMap[$value];
157
                $array['LogLevelCode'] = $value;
158
                break;
159
            case 'level_name':
160
                break;
161
162
            case 'extra':
163
                $array = $this->processExtras($array, $value);
164
                break;
165
166
            case 'context':
167
                $array = $this->processContext($array, $value);
168
                break;
169
170
            default:
171
                $array[is_int($key) ? $key : SeqCompactJsonFormatter::ConvertSnakeCaseToPascalCase($key)] = $this->normalize($value);
172
                break;
173
        }
174
175
        return $array;
176
    }
177
178
    private function processMessage($array, $value)
179
    {
180
        $array['@m'] = $value;
181
        if (!(strpos($value, '{') === false)) {
182
            $array['@mt'] = $value;
183
        }
184
185
        return $array;
186
    }
187
188
    private function processDateTime($array, $value)
189
    {
190
        if ($value instanceof \DateTime) {
191
            $value = $value->format(DateTime::ISO8601);
192
        }
193
        $array['@t'] = $value;
194
195
        return $array;
196
    }
197
198
    private function processExtras($array, $value)
199
    {
200
        if (is_array($value) && is_array($normalizedArray = $this->normalize($value))) {
201
            if ($this->extractExtras) {
202
                $array = array_merge($normalizedArray, $array);
203
            } else {
204
                $array['Extra'] = $normalizedArray;
205
            }
206
        }
207
208
        return $array;
209
    }
210
211
    private function processContext($array, $value)
212
    {
213
        if (is_array($value)) {
214
            $exception = $this->extractException($value);
215
            $normalizedArray = $this->normalize($value);
216
217
            if (is_array($normalizedArray)) {
218
                if ($this->extractContext) {
219
                    $array = array_merge($normalizedArray, $array);
220
                } else {
221
                    $array['Context'] = $normalizedArray;
222
                }
223
            }
224
225
            if ($exception !== null) {
226
                if ($exception instanceof \Throwable) {
0 ignored issues
show
introduced by
$exception is always a sub-type of Throwable.
Loading history...
227
                    $exception = $this->normalizeException($exception);
228
                }
229
230
                $array['@x'] = $exception;
231
            }
232
        }
233
234
        return $array;
235
    }
236
}