Completed
Branch master (a89fae)
by Michał
03:16
created

Raven::write()   F

Complexity

Conditions 19
Paths 6144

Size

Total Lines 68
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 42
nc 6144
nop 1
dl 0
loc 68
rs 0.3499
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dziki\MonologSentryBundle\Handler;
6
7
use Monolog\Handler\RavenHandler;
8
use Monolog\Logger;
9
use Raven_Client;
10
11
class Raven extends RavenHandler
12
{
13
    /**
14
     * Because of https://github.com/Seldaek/monolog/pull/1179
15
     */
16
    protected $logLevels = [
17
        Logger::DEBUG => Raven_Client::DEBUG,
18
        Logger::INFO => Raven_Client::INFO,
19
        Logger::NOTICE => Raven_Client::INFO,
20
        Logger::WARNING => Raven_Client::WARNING,
21
        Logger::ERROR => Raven_Client::ERROR,
22
        Logger::CRITICAL => Raven_Client::FATAL,
23
        Logger::ALERT => Raven_Client::FATAL,
24
        Logger::EMERGENCY => Raven_Client::FATAL,
25
    ];
26
    /**
27
     * Because of https://github.com/Seldaek/monolog/pull/1179
28
     *
29
     * @var string
30
     */
31
    protected $release;
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function handleBatch(array $records): void
37
    {
38
        $level = $this->level;
39
40
        // filter records based on their level
41
        $records = array_filter(
42
            $records,
43
            function ($record) use ($level) {
44
                return $record['level'] >= $level;
45
            }
46
        );
47
48
        if (!$records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
49
            return;
50
        }
51
52
        // the record with the highest severity is the "main" one
53
        $record = array_reduce(
54
            $records,
55
            function ($highest, $record) {
56
                if ($record['level'] > $highest['level']) {
57
                    return $record;
58
                }
59
60
                return $highest;
61
            }
62
        );
63
64
        // the other ones are added as a context item
65
        $logs = [];
66
        foreach ($records as $r) {
67
            $log = $this->processRecord($r);
68
69
            $date = $log['datetime'] ?? time();
70
71
            $crumb = [
72
                'category' => $log['channel'],
73
                'message' => $log['message'],
74
                'level' => strtolower($log['level_name']),
75
                'timestamp' => (float)($date instanceof \DateTime ? $date->format('U.u') : $date),
76
            ];
77
78
            if (array_key_exists('context', $log)) {
79
                if ($log['channel'] === 'request' && array_key_exists('route_parameters', $log['context'])) {
80
                    $crumb['data']['route'] = $log['context']['route_parameters']['_route'];
81
                    $crumb['data']['controller'] = $log['context']['route_parameters']['_controller'];
82
                    $crumb['data']['uri'] = $log['context']['request_uri'];
83
                }
84
85
                if ($log['channel'] === 'security' && array_key_exists('user', $log['context'])) {
86
                    $crumb['data']['user'] = $log['context']['user']['username'];
87
                }
88
            }
89
90
            $this->ravenClient->breadcrumbs->record($crumb);
91
        }
92
93
        if ($logs) {
0 ignored issues
show
introduced by
$logs is an empty array, thus is always false.
Loading history...
Bug Best Practice introduced by
The expression $logs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
94
            $record['context']['logs'] = (string)$this->getBatchFormatter()->formatBatch($logs);
95
        }
96
97
        $this->handle($record);
98
    }
99
100
    /**
101
     * Because of https://github.com/Seldaek/monolog/pull/1179
102
     *
103
     * @param array $record
104
     */
105
    protected function write(array $record): void
106
    {
107
        $previousUserContext = false;
108
        $options = [];
109
        $options['level'] = $this->logLevels[$record['level']];
110
        $options['tags'] = [];
111
112
        if (!empty($record['extra']['tags'])) {
113
            $options['tags'] = array_merge($options['tags'], $record['extra']['tags']);
114
            unset($record['extra']['tags']);
115
        }
116
117
        if (!empty($record['context']['tags'])) {
118
            $options['tags'] = array_merge($options['tags'], $record['context']['tags']);
119
            unset($record['context']['tags']);
120
        }
121
122
        if (!empty($record['context']['fingerprint'])) {
123
            $options['fingerprint'] = $record['context']['fingerprint'];
124
            unset($record['context']['fingerprint']);
125
        }
126
127
        if (!empty($record['context']['logger'])) {
128
            $options['logger'] = $record['context']['logger'];
129
            unset($record['context']['logger']);
130
        } else {
131
            $options['logger'] = $record['channel'];
132
        }
133
134
        foreach ($this->getExtraParameters() as $key) {
135
            foreach (['extra', 'context'] as $source) {
136
                if (!empty($record[$source][$key])) {
137
                    $options[$key] = $record[$source][$key];
138
                    unset($record[$source][$key]);
139
                }
140
            }
141
        }
142
143
        if (!empty($record['context'])) {
144
            $options['extra']['context'] = $record['context'];
145
            if (!empty($record['context']['user'])) {
146
                $previousUserContext = $this->ravenClient->context->user;
147
                $this->ravenClient->user_context($record['context']['user']);
148
                unset($options['extra']['context']['user']);
149
            }
150
        }
151
152
        if (!empty($record['contexts'])) {
153
            $options['contexts'] = $record['contexts'];
154
        }
155
156
        if (!empty($record['extra'])) {
157
            $options['extra']['extra'] = $record['extra'];
158
        }
159
160
        if (!empty($this->release) && !isset($options['release'])) {
161
            $options['release'] = $this->release;
162
        }
163
164
        if (isset($record['context']['exception']) && ($record['context']['exception'] instanceof \Exception || (PHP_VERSION_ID >= 70000 && $record['context']['exception'] instanceof \Throwable))) {
165
            $options['extra']['message'] = $record['formatted'];
166
            $this->ravenClient->captureException($record['context']['exception'], $options);
167
        } else {
168
            $this->ravenClient->captureMessage($record['formatted'], [], $options);
169
        }
170
171
        if ($previousUserContext !== false) {
172
            $this->ravenClient->user_context($previousUserContext);
173
        }
174
    }
175
}
176