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