1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NotificationChannels\WebPush; |
4
|
|
|
|
5
|
|
|
use Minishlink\WebPush\WebPush; |
6
|
|
|
use Illuminate\Notifications\Notification; |
7
|
|
|
use Minishlink\WebPush\MessageSentReport; |
8
|
|
|
|
9
|
|
|
class WebPushChannel |
10
|
|
|
{ |
11
|
|
|
/** @var \Minishlink\WebPush\WebPush */ |
12
|
|
|
protected $webPush; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @param \Minishlink\WebPush\WebPush $webPush |
16
|
|
|
* @return void |
|
|
|
|
17
|
|
|
*/ |
18
|
|
|
public function __construct(WebPush $webPush) |
19
|
|
|
{ |
20
|
|
|
$this->webPush = $webPush; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Send the given notification. |
25
|
|
|
* |
26
|
|
|
* @param mixed $notifiable |
27
|
|
|
* @param \Illuminate\Notifications\Notification $notification |
28
|
|
|
* @return void |
29
|
|
|
*/ |
30
|
|
|
public function send($notifiable, Notification $notification) |
31
|
|
|
{ |
32
|
|
|
$subscriptions = $notifiable->routeNotificationFor('WebPush'); |
33
|
|
|
|
34
|
|
|
if (! $subscriptions || $subscriptions->isEmpty()) { |
35
|
|
|
return; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$payload = json_encode($notification->toWebPush($notifiable, $notification)->toArray()); |
|
|
|
|
39
|
|
|
|
40
|
|
|
$subscriptions->each(function ($sub) use ($payload) { |
41
|
|
|
$subscription = new \Minishlink\WebPush\Subscription($sub->endpoint, $sub->public_key, $sub->auth_token, $sub->content_encoding); |
42
|
|
|
$this->webPush->sendNotification($subscription, $payload); |
43
|
|
|
}); |
44
|
|
|
|
45
|
|
|
$reports = $this->webPush->flush(); |
46
|
|
|
|
47
|
|
|
$this->deleteInvalidSubscriptions($reports, $subscriptions); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param \Generator|MessageSentReport $response |
52
|
|
|
* @param \Illuminate\Database\Eloquent\Collection $subscriptions |
53
|
|
|
* @return void |
54
|
|
|
*/ |
55
|
|
|
protected function deleteInvalidSubscriptions($response, $subscriptions) |
56
|
|
|
{ |
57
|
|
|
foreach ($response as $report) { |
58
|
|
|
/** @var MessageSentReport $report */ |
59
|
|
|
if (! $report->isSuccess()) { |
60
|
|
|
$subscriptions->each(function($s) use($report) { |
61
|
|
|
if($s->endpoint === $report->getEndpoint()) { |
62
|
|
|
logger()->warning('deleting subscription cause of ' . $report->getReason()); |
63
|
|
|
$s->delete(); |
64
|
|
|
} |
65
|
|
|
}); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Adding a
@return
annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.Please refer to the PHP core documentation on constructors.