1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\FailedJobMonitor; |
4
|
|
|
|
5
|
|
|
use Illuminate\Notifications\ChannelManager; |
6
|
|
|
use Illuminate\Queue\Events\JobFailed; |
7
|
|
|
use Illuminate\Queue\QueueManager; |
8
|
|
|
use Spatie\FailedJobMonitor\Exceptions\InvalidNotifiableException; |
9
|
|
|
use Spatie\FailedJobMonitor\Exceptions\InvalidNotificationException; |
10
|
|
|
|
11
|
|
|
class FailedJobNotifier |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
public function register() |
15
|
|
|
{ |
16
|
|
|
$mapping = collect(config('laravel-failed-job-monitor')); |
17
|
|
|
|
18
|
|
|
app(QueueManager::class)->failing(function (JobFailed $event) use ($mapping) { |
19
|
|
|
if ($mapping->has($event->job->resolveName())) { |
20
|
|
|
$this->handle($mapping->get($event->job->resolveName()), $event); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
if ($mapping->has('*')) { |
24
|
|
|
$this->handle($mapping->get('*'), $event); |
25
|
|
|
} |
26
|
|
|
}); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function isValidNotificationClass($notificationClass):bool |
30
|
|
|
{ |
31
|
|
|
return $notificationClass === Notification::class || is_subclass_of($notificationClass, Notification::class); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
private function handle($map, $event) |
35
|
|
|
{ |
36
|
|
|
$notifiable = new $map['notifiable']; |
37
|
|
|
$notificationClass = $map['notification']; |
38
|
|
|
$filterMethod = array_get($map, 'filter', 'canBeNotifiedAboutFailedJobs'); |
39
|
|
|
|
40
|
|
|
if (!method_exists($notifiable, 'scope' . ucfirst($filterMethod))) { |
41
|
|
|
throw new InvalidNotifiableException( |
42
|
|
|
sprintf('Class %s have scope%s method', $map['notifiable'], ucfirst($filterMethod)) |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if (!$this->isValidNotificationClass($notificationClass)) { |
47
|
|
|
throw new InvalidNotificationException( |
48
|
|
|
"Class {$notificationClass} must extend " . Notification::class |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$notifiables = $notifiable->newQuery()->$filterMethod()->get(); |
53
|
|
|
$notification = new $notificationClass($event, array_get($map, 'via', [])); |
54
|
|
|
|
55
|
|
|
app(ChannelManager::class)->send($notifiables, $notification); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|