Completed
Push — master ( a10ad6...262a1e )
by Russell
20:23
created

SentryMonologHandler::write()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 12
nc 3
nop 1
1
<?php
2
3
/**
4
 * Class: SentryMonologHandler.
5
 *
6
 * @author  Russell Michell 2017 <[email protected]>
7
 * @package phptek/sentry
8
 */
9
10
namespace PhpTek\Sentry\Handler;
11
12
use Monolog\Handler\RavenHandler,
13
    Monolog\Logger,
14
    SilverStripe\Dev\Backtrace,
15
    SilverStripe\Security\Member,
16
    PhpTek\Sentry\Log\SentryLogger;
17
18
/**
19
 * Monolog Handler for Sentry via Raven
20
 */
21
22
class SentryMonologHandler extends RavenHandler
23
{    
0 ignored issues
show
Coding Style introduced by
The opening class brace should be on a newline by itself.
Loading history...
24
    /**
25
     * @var SentryClientAdaptor
26
     */
27
    protected $client;
28
29
    /**
30
     * @param  int   $level
31
     * @param  bool  $bubble
32
     * @param  array $extras Extra parameters that will become "tags" in Sentry.
33
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
34
     */
35
    public function __construct($level = Logger::DEBUG, $bubble = true, $extras = [])
36
    {        
37
        // Returns an instance of {@link SentryLogger}
38
        $logger = SentryLogger::factory($extras);
39
        $sdk = $logger->client->getSDK();
0 ignored issues
show
Bug introduced by
The property client does not seem to exist in PhpTek\Sentry\Log\SentryLogger.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
40
        $this->client = $logger->client;
41
        $this->client->setData('user', $this->getUserData(null, $logger));
42
        
43
        parent::__construct($sdk, $level, $bubble);
44
    }
45
    
46
    /**
47
     * @return SentryClientAdaptor
48
     */
49
    public function getClient()
50
    {
51
        return $this->client;
52
    }
53
    
54
    /**
55
     * write() forms the entry point into the physical sending of the error. The 
56
     * sending itself is done by the current adaptor's `send()` method.
57
     * 
58
     * @param  array $record An array of error-context metadata with the following 
59
     *                       available keys:
60
     * 
61
     *                       - message
62
     *                       - context
63
     *                       - level
64
     *                       - level_name
65
     *                       - channel
66
     *                       - datetime
67
     *                       - extra
68
     *                       - formatted
69
     * 
70
     * @return void
71
     */
72
    protected function write(array $record)
73
    {   
74
        // The complete compliment of these data come via the Raven_Client::xxx_context() methods
75
        // Monolog does not make use of the 'extra' parameter, so we munge ours into
76
        // its 'context' param and use that
77
        if (!$extra = !empty($record['extra']) ? $record['extra'] : []) {
78
            $extra = !empty($record['context']) ? $record['context'] : [];
79
        }
80
81
        $record = [
82
            'level'      => $record['level'],
83
            'formatted'  => $record['formatted'],
84
            'channel'    => $record['channel'],
85
            'timestamp'  => $record['datetime']->getTimestamp(),
86
            'extra'      => $extra,
87
            'stacktrace' => $this->backtrace($record),
88
            'stack'      => true,
89
        ];
90
        
91
        // write() calls one of RavenHandler::captureException() or RavenHandler::captureMessage()
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
92
        // depending on 
93
        parent::write($record);
94
    }
95
    
96
    /**
97
     * Generate a cleaned-up backtrace of the event that got us here.
98
     * 
99
     * @param  array $record
100
     * @return array
101
     */
102
    private function backtrace($record)
0 ignored issues
show
Unused Code introduced by
The parameter $record is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
103
    {
104
        $bt = debug_backtrace();
105
            
106
        // Push current line into context
107
        array_unshift($bt, [
108
            'file' => !empty($bt['file']) ? $bt['file'] : 'N/A',
109
            'line' => !empty($bt['line']) ? $bt['line'] : 'N/A',
110
            'function' => '',
111
            'class' => '',
112
            'type' => '',
113
            'args' => [],
114
        ]);
115
        
116
        $bt = Backtrace::filter_backtrace($bt, [
117
            'PhpTek\Sentry\Handler\SentryMonologHandler->write',
118
            'PhpTek\Sentry\Handler\SentryMonologHandler->backtrace',
119
        ]);
120
        
121
        return $bt;
122
    }
123
    
124
    /**
125
     * Returns a default set of additional data specific to the user's part in
126
     * the request.
127
     * 
128
     * @param  Member $member
129
     * @return array
130
     */
131
    private function getUserData(Member $member = null, $logger)
132
    {
133
        if (!$member) {
134
            $member = Member::currentUser();
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\Security\Member::currentUser() has been deprecated with message: 5.0.0 use Security::getCurrentUser()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
135
        }
136
        
137
        return [
138
            'IPddress'  => $logger->getIP(),
139
            'ID'        => $member ? $member->getField('ID') : SentryLogger::SLW_NOOP,
140
            'Email'     => $member ? $member->getField('Email') : SentryLogger::SLW_NOOP,
141
        ];
142
    }
143
    
144
}
145