Passed
Push — develop ( 5d1410...3b4c3a )
by Nikolay
04:03
created

SentryErrorLogger   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 42
c 2
b 0
f 0
dl 0
loc 81
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 3
A captureException() 0 3 1
B init() 0 34 7
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright (C) 2017-2020 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
declare(strict_types=1);
21
22
namespace MikoPBX\Core\System;
23
24
use Sentry\ClientBuilder;
25
use Sentry\SentrySdk;
26
use Sentry\State\Scope;
27
use Throwable;
28
29
/**
30
 * Collects errors and send them to Sentry cloud for software improvement reasons
31
 */
32
class SentryErrorLogger
33
{
34
35
    protected string $dsn; // Sentry unique ID
36
    protected string $libraryName;
37
    protected string $licKey;
38
    protected string $companyName;
39
    protected string $email;
40
    protected string $release; // MikoPBX release
41
    protected string $environment; // development or production
42
    protected bool $enabled; // MikoPBX general settings "send errors to developers"
43
44
45
    public function __construct($libraryName)
46
    {
47
        $this->dsn         = 'https://[email protected]/1';
48
        $this->libraryName = $libraryName;
49
        $this->environment = 'development';
50
        if (file_exists('/tmp/licenseInfo')) {
51
            $licenseInfo       = json_decode(file_get_contents('/tmp/licenseInfo', false));
52
            $this->licKey      = $licenseInfo->{'@attributes'}->key;
53
            $this->email       = $licenseInfo->{'@attributes'}->email;
54
            $this->companyName = $licenseInfo->{'@attributes'}->companyname;
55
        }
56
        if (file_exists('/etc/version')) {
57
            $pbxVersion    = str_replace("\n", "", file_get_contents('/etc/version', false));
58
            $this->release = "mikopbx@{$pbxVersion}";
59
        }
60
        $this->enabled = file_exists('/tmp/sendmetrics');
61
    }
62
63
    /**
64
     * Если в настройках PBX разрешено отправлять сообщения об ошибках на сервер,
65
     * то функция инициализирует подпистему облачного логирования ошибок Sentry
66
     *
67
     * @return Boolean - initialization result
68
     */
69
    public function init(): bool
70
    {
71
        if ($this->enabled) {
72
            $options = [
73
                'dsn'         => $this->dsn,
74
                'release'     => $this->release,
75
                'environment' => $this->environment,
76
            ];
77
            if ($this->environment === 'development') {
78
                $options['traces_sample_rate'] = '1.0';
79
            }
80
            $client = ClientBuilder::create($options)->getClient();
81
82
            SentrySdk::init()->bindClient($client);
83
84
            SentrySdk::getCurrentHub()->configureScope(
85
                function (Scope $scope): void {
86
                    if (isset($this->email)) {
87
                        $scope->setUser(['id' => $this->email]);
88
                    }
89
                    if (isset($this->licKey)) {
90
                        $scope->setExtra('key', $this->licKey);
91
                    }
92
                    if (isset($this->companyName)) {
93
                        $scope->setExtra('company', $this->companyName);
94
                    }
95
                    if (isset($this->libraryName)) {
96
                        $scope->setTag('library', $this->libraryName);
97
                    }
98
                }
99
            );
100
        }
101
102
        return $this->enabled;
103
    }
104
105
    /**
106
     * Process errors and send it to sentry cloud
107
     *
108
     * @param Throwable $e
109
     */
110
    public function captureException(Throwable $e): void
111
    {
112
        SentrySdk::getCurrentHub()->captureException($e);
113
    }
114
}
115
116