Raven::setRelease()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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
    public function setRelease($release)
34
    {
35
        $this->release = $release;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function handleBatch(array $records): void
42
    {
43
        $level = $this->level;
44
45
        // filter records based on their level
46
        $records = array_filter(
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $records. This often makes code more readable.
Loading history...
47
            $records,
48
            function ($record) use ($level) {
49
                return $record['level'] >= $level;
50
            }
51
        );
52
53
        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...
54
            return;
55
        }
56
57
        // the record with the highest severity is the "main" one
58
        $record = array_reduce(
59
            $records,
60
            function ($highest, $record) {
61
                if ($record['level'] > $highest['level']) {
62
                    return $record;
63
                }
64
65
                return $highest;
66
            },
67
            reset($records)
68
        );
69
70
        foreach ($records as $r) {
71
            $log = $this->processRecord($r);
72
73
            $date = $log['datetime'] ?? time();
74
75
            $crumb = [
76
                'category' => $log['channel'],
77
                'message' => $log['message'],
78
                'level' => strtolower($log['level_name']),
79
                'timestamp' => (float) ($date instanceof \DateTimeInterface ? $date->format('U.u') : $date),
80
            ];
81
82
            if (array_key_exists('context', $log)) {
83
                if ('request' === $log['channel'] && array_key_exists('route_parameters', $log['context'])) {
84
                    $crumb['data']['route'] = $log['context']['route_parameters']['_route'];
85
                    $crumb['data']['controller'] = $log['context']['route_parameters']['_controller'];
86
                    $crumb['data']['uri'] = $log['context']['request_uri'];
87
                } elseif ('security' === $log['channel'] && array_key_exists('user', $log['context'])) {
88
                    $crumb['data']['user'] = $log['context']['user']['username'];
89
                } else {
90
                    $crumb['data'] = $log['context'];
91
                }
92
            }
93
94
            $this->ravenClient->breadcrumbs->record($crumb);
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 View Code Duplication
        if (!empty($record['context']['tags'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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 View Code Duplication
        if (!empty($record['context']['logger'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
        $this->ravenClient->breadcrumbs->reset();
172
173
        if (false !== $previousUserContext) {
174
            $this->ravenClient->user_context($previousUserContext);
0 ignored issues
show
Bug introduced by
It seems like $previousUserContext can also be of type null; however, Raven_Client::user_context() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
175
        }
176
    }
177
}
178