Completed
Push — master ( 42edb2...d38aea )
by Russell
08:56 queued 10s
created

SentryAdaptor::getData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * Class: SentryAdaptor.
5
 *
6
 * @author  Russell Michell 2017-2019 <[email protected]>
7
 * @package phptek/sentry
8
 */
9
10
namespace PhpTek\Sentry\Adaptor;
11
12
use Sentry\State\Hub;
13
use Sentry\ClientBuilder;
14
use Sentry\State\Scope;
15
use Sentry\Severity;
16
use Sentry\ClientInterface;
17
use SilverStripe\Core\Config\Configurable;
18
use SilverStripe\Core\Injector\Injector;
19
20
/**
21
 * The SentryAdaptor provides a functionality bridge between the getsentry/sentry
22
 * PHP SDK and {@link SentryLogger} itself.
23
 */
24
class SentryAdaptor
25
{
26
    use Configurable;
27
28
    /**
29
     * @var ClientInterface
30
     */
31
    protected $sentry;
32
33
    /**
34
     * @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...
35
     */
36
    public function __construct()
37
    {
38
        $client = ClientBuilder::create($this->getOpts() ?: [])->getClient();
39
        Hub::setCurrent(new Hub($client));
40
41
        $this->sentry = $client;
42
    }
43
44
    /**
45
     * @return ClientInterface
46
     */
47
    public function getSDK() : ClientInterface
48
    {
49
        return $this->sentry;
50
    }
51
52
    /**
53
     * @param  string $field
54
     * @param  mixed  $data
55
     * @return void
56
     * @throws SentryLogWriterException
57
     */
58
    public function setData(string $field, $data) : void
59
    {
60
        $options = Hub::getCurrent()->getClient()->getOptions();
61
62
        switch ($field) {
63
            case 'env':
64
                $options->setEnvironment($data);
65
                break;
66 View Code Duplication
            case '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...
67
                Hub::getCurrent()->configureScope(function (Scope $scope) use($data) : void {
68
                    foreach ($data as $tagName => $tagData) {
69
                        $scope->setTag($tagName, $tagData);
70
                    }
71
                });
72
                break;
73
            case 'user':
74
                Hub::getCurrent()->configureScope(function (Scope $scope) use($data) : void {
75
                    $scope->setUser($data);
76
                });
77
                break;
78 View Code Duplication
            case 'extra':
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...
79
                Hub::getCurrent()->configureScope(function (Scope $scope) use($data) : void {
80
                    foreach ($data as $extraKey => $extraData) {
81
                        $scope->setExtra($extraKey, $extraData);
82
                    }
83
                });
84
                break;
85
            case 'level':
86
                Hub::getCurrent()->configureScope(function (Scope $scope) use($data) : void {
87
                    $scope->setLevel(new Severity(strtolower($data)));
88
                });
89
                break;
90
            default:
91
                $msg = sprintf('Unknown field "%s" passed to %s().', $field, __FUNCTION__);
92
                throw new SentryLogWriterException($msg);
93
        }
94
    }
95
96
    /**
97
     * Simple getter for data set to / on the sentry client.
98
     *
99
     * @return array
100
     */
101
    public function getData() : array
102
    {
103
        $options = Hub::getCurrent()->getClient()->getOptions();
104
        $data = [];
105
106
        Hub::getCurrent()->configureScope(function (Scope $scope) use (&$data) : void {
107
                $data['user'] = $scope->getUser();
108
                $data['tags'] = $scope->getTags();
109
                $data['extra'] = $scope->getExtra();
110
        });
111
112
        return [
113
            'env'   => $options->getEnvironment(),
114
            'tags'  => $data['tags'] ?? [],
115
            'user'  => $data['user'] ?? [],
116
            'extra' => $data['extra'] ?? [],
117
        ];
118
    }
119
120
    /**
121
     * Get various userland options to pass to Raven. Includes detecting and setting
122
     * proxy options too.
123
     *
124
     * @param  string $opt
125
     * @return mixed  string|array|null depending on whether $opts is passed.
126
     */
127
    protected function getOpts(string $opt = '')
128
    {
129
        // Extract env-vars from YML config
130
        $opts = Injector::inst()->convertServiceProperty($this->config()->get('opts'));
131
132
        // Deal with proxy settings. Raven_Client permits host:port format but SilverStripe's
133
        // YML config only permits single backtick-enclosed env/consts per config
134
        if (!empty($opts['http_proxy'])) {
135
            if (!empty($opts['http_proxy']['host']) && !empty($opts['http_proxy']['port'])) {
136
                $opts['http_proxy'] = sprintf(
137
                    '%s:%s',
138
                    $opts['http_proxy']['host'],
139
                    $opts['http_proxy']['port']
140
                );
141
            }
142
        }
143
144
        if ($opt && !empty($opts[$opt])) {
145
            // Return one
146
            return $opts[$opt];
147
        } else if (!$opt) {
148
            // Return all
149
            return $opts;
150
        }
151
152
        return null;
153
    }
154
}
155