SentryNotifier::reportSentryNotification()   A
last analyzed

Complexity

Conditions 5
Paths 11

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 13
c 5
b 1
f 0
dl 0
loc 22
rs 9.5222
cc 5
nc 11
nop 1
1
<?php
2
3
namespace Skater4\LaravelSentryNotifications\Services;
4
5
use Log;
6
use Skater4\LaravelSentryNotifications\Services\Messengers\Factories\MessengerClientFactory;
7
use Skater4\LaravelSentryNotifications\Exceptions\SentryNotifierException;
8
use Skater4\LaravelSentryNotifications\Exceptions\UnknownServiceException;
9
use Skater4\LaravelSentryNotifications\Services\Sentry\Interfaces\SentryServiceInterface;
10
use Throwable;
11
12
class SentryNotifier
13
{
14
    private $messengerClient;
15
    private $sentryService;
16
    private $dontReport = [
17
        SentryNotifierException::class,
18
        UnknownServiceException::class
19
    ];
20
21
    public function __construct(SentryServiceInterface $sentryService)
22
    {
23
        $this->sentryService = $sentryService;
24
    }
25
26
    public function reportSentryNotification(Throwable $e): void
27
    {
28
        if (!$this->canReportSentry($e)) {
29
            return;
30
        }
31
32
        if (!$this->messengerClient) {
33
            $this->messengerClient = app(MessengerClientFactory::class)->create();
34
        }
35
36
        try {
37
            $eventId = $this->sentryService->captureException($e);
38
39
            if (empty($eventId)) {
40
                throw new SentryNotifierException('Empty Event ID response');
41
            }
42
43
            $issueUrl = $this->sentryService->getIssueUrl($eventId);
44
            $this->messengerClient->sendMessage($e, $issueUrl);
45
        } catch (Throwable $_e) {
46
            Log::error(get_class($e) . 'Exception: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
47
            throw new SentryNotifierException('Sentry Notifier error: ' . $_e->getMessage()
48
            );
49
        }
50
    }
51
52
    private function canReportSentry(Throwable $e): bool
53
    {
54
        return !in_array(get_class($e), $this->dontReport) && !empty(config('services.laravel-sentry-notifications.service'));
55
    }
56
}
57