Completed
Push — master ( 956ded...a083a0 )
by Freek
02:22
created

Notifier::backupHasFailed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 7
nc 2
nop 2
1
<?php
2
3
namespace Spatie\Backup\Notifications;
4
5
use Illuminate\Contracts\Logging\Log as LogContract;
6
use Spatie\Backup\BackupDestination\BackupDestination;
7
use Spatie\Backup\Tasks\Monitor\BackupDestinationStatus;
8
use Exception;
9
10
class Notifier
11
{
12
    /** @var array */
13
    protected $config;
14
15
    /** @var \Illuminate\Contracts\Logging\Log */
16
    protected $log;
17
18
    /**
19
     * @param \Illuminate\Contracts\Logging\Log $log
20
     */
21
    public function __construct(LogContract $log)
22
    {
23
        $this->log = $log;
24
25
        $this->subject = config('laravel-backup.backup.name').' backups';
0 ignored issues
show
Bug introduced by
The property subject does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
26
    }
27
28
    public function backupWasSuccessful()
29
    {
30
        $this->sendNotification(
31
            'whenBackupWasSuccessful',
32
            $this->subject,
33
            'Successfully took a new backup',
34
            BaseSender::TYPE_SUCCESS
35
        );
36
    }
37
38
    public function backupHasFailed(Exception $exception, BackupDestination $backupDestination = null)
39
    {
40
        $extraMessage = $backupDestination ? "to {$backupDestination->getFilesystemType()}-filesystem" : '';
41
42
        $this->sendNotification(
43
            'whenBackupHasFailed',
44
            "{$this->subject} : error",
45
            "Failed to backup {$extraMessage} because: {$exception->getMessage()}",
46
            BaseSender::TYPE_ERROR
47
        );
48
    }
49
50
    public function cleanupWasSuccessful(BackupDestination $backupDestination)
51
    {
52
        $this->sendNotification(
53
            'whenCleanupWasSuccessful',
54
            $this->subject,
55
            "Successfully cleaned up the backups on {$backupDestination->getFilesystemType()}-filesystem",
56
            BaseSender::TYPE_SUCCESS
57
        );
58
    }
59
60
    public function cleanupHasFailed(Exception $exception)
61
    {
62
        $this->sendNotification(
63
            'whenCleanupHasFailed',
64
            "{$this->subject} : error",
65
            "Failed to cleanup the backup because: {$exception->getMessage()}",
66
            BaseSender::TYPE_ERROR
67
        );
68
    }
69
70
    public function healthyBackupWasFound(BackupDestinationStatus $backupDestinationStatus)
71
    {
72
        $this->sendNotification(
73
            'whenHealthyBackupWasFound',
74
            "Healthy backup found for {$backupDestinationStatus->getBackupName()} on {$backupDestinationStatus->getFilesystemName()}-filesystem",
0 ignored issues
show
Deprecated Code introduced by
The method Spatie\Backup\Tasks\Moni...us::getFilesystemName() has been deprecated.

This method has been deprecated.

Loading history...
75
            "Backups on filesystem {$backupDestinationStatus->getFilesystemName()} are ok",
0 ignored issues
show
Deprecated Code introduced by
The method Spatie\Backup\Tasks\Moni...us::getFilesystemName() has been deprecated.

This method has been deprecated.

Loading history...
76
            BaseSender::TYPE_SUCCESS
77
        );
78
    }
79
80
    /**
81
     * @param \Spatie\Backup\Tasks\Monitor\BackupDestinationStatus $backupDestinationStatus
82
     */
83
    public function unhealthyBackupWasFound(BackupDestinationStatus $backupDestinationStatus)
84
    {
85
        $this->sendNotification(
86
            'whenUnhealthyBackupWasFound',
87
            "Unhealthy backup found for {$backupDestinationStatus->getBackupName()} on {$backupDestinationStatus->getFilesystemName()}-filesystem",
0 ignored issues
show
Deprecated Code introduced by
The method Spatie\Backup\Tasks\Moni...us::getFilesystemName() has been deprecated.

This method has been deprecated.

Loading history...
88
            UnhealthyBackupMessage::createForBackupDestinationStatus($backupDestinationStatus),
89
            BaseSender::TYPE_ERROR
90
        );
91
    }
92
93
    /**
94
     * @param string $eventName
95
     * @param string $subject
96
     * @param string $message
97
     * @param string $type
98
     */
99
    protected function sendNotification($eventName, $subject, $message, $type)
100
    {
101
        $senderNames = config("laravel-backup.notifications.events.{$eventName}");
102
103
        collect($senderNames)
104
            ->map(function ($senderName) {
105
                $className = $senderName;
106
107
                if (file_exists(__DIR__.'/Senders/'.ucfirst($senderName).'.php')) {
108
                    $className = '\\Spatie\\Backup\\Notifications\\Senders\\'.ucfirst($senderName);
109
                }
110
111
                return app($className);
112
            })
113
            ->each(function (SendsNotifications $sender) use ($subject, $message, $type) {
114
                try {
115
                    $sender
116
                        ->setSubject($subject)
117
                        ->setMessage($message)
118
                        ->setType($type)
119
                        ->send();
120
                } catch (Exception $exception) {
121
                    $errorMessage = "Laravel-backup notifier failed because {$exception->getMessage()}"
122
                        .PHP_EOL
123
                        .$exception->getTraceAsString();
124
125
                    $this->log->error($errorMessage);
126
                    consoleOutput()->error($errorMessage);
0 ignored issues
show
Documentation Bug introduced by
The method error does not exist on object<Spatie\Backup\Helpers\ConsoleOutput>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
127
                }
128
            });
129
    }
130
}
131