EventHandler   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 59
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A subscribe() 0 10 1
A determineNotifiable() 0 6 1
A determineNotification() 0 18 2
A allBackupEventClasses() 0 11 1
1
<?php
2
3
namespace Spatie\Backup\Notifications;
4
5
use Illuminate\Contracts\Config\Repository;
6
use Illuminate\Contracts\Events\Dispatcher;
7
use Illuminate\Notifications\Notification;
8
use Spatie\Backup\Events\BackupHasFailed;
9
use Spatie\Backup\Events\BackupWasSuccessful;
10
use Spatie\Backup\Events\CleanupHasFailed;
11
use Spatie\Backup\Events\CleanupWasSuccessful;
12
use Spatie\Backup\Events\HealthyBackupWasFound;
13
use Spatie\Backup\Events\UnhealthyBackupWasFound;
14
use Spatie\Backup\Exceptions\NotificationCouldNotBeSent;
15
16
class EventHandler
17
{
18
    /** @var \Illuminate\Contracts\Config\Repository */
19
    protected $config;
20
21
    public function __construct(Repository $config)
22
    {
23
        $this->config = $config;
24
    }
25
26
    public function subscribe(Dispatcher $events)
27
    {
28
        $events->listen($this->allBackupEventClasses(), function ($event) {
29
            $notifiable = $this->determineNotifiable();
30
31
            $notification = $this->determineNotification($event);
32
33
            $notifiable->notify($notification);
34
        });
35
    }
36
37
    protected function determineNotifiable()
38
    {
39
        $notifiableClass = $this->config->get('backup.notifications.notifiable');
40
41
        return app($notifiableClass);
42
    }
43
44
    protected function determineNotification($event): Notification
45
    {
46
        $eventName = class_basename($event);
47
48
        $notificationClass = collect($this->config->get('backup.notifications.notifications'))
49
            ->keys()
50
            ->first(function ($notificationClass) use ($eventName) {
51
                $notificationName = class_basename($notificationClass);
52
53
                return $notificationName === $eventName;
54
            });
55
56
        if (! $notificationClass) {
57
            throw NotificationCouldNotBeSent::noNotificationClassForEvent($event);
58
        }
59
60
        return app($notificationClass)->setEvent($event);
61
    }
62
63
    protected function allBackupEventClasses(): array
64
    {
65
        return [
66
            BackupHasFailed::class,
67
            BackupWasSuccessful::class,
68
            CleanupHasFailed::class,
69
            CleanupWasSuccessful::class,
70
            HealthyBackupWasFound::class,
71
            UnhealthyBackupWasFound::class,
72
        ];
73
    }
74
}
75