|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace NotificationChannels\WebPush; |
|
4
|
|
|
|
|
5
|
|
|
use Minishlink\WebPush\WebPush; |
|
6
|
|
|
use Illuminate\Notifications\Notification; |
|
7
|
|
|
|
|
8
|
|
|
class WebPushChannel |
|
9
|
|
|
{ |
|
10
|
|
|
/** @var \Minishlink\WebPush\WebPush */ |
|
11
|
|
|
protected $webPush; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @param \Minishlink\WebPush\WebPush $webPush |
|
15
|
|
|
* @return void |
|
|
|
|
|
|
16
|
|
|
*/ |
|
17
|
|
|
public function __construct(WebPush $webPush) |
|
18
|
|
|
{ |
|
19
|
|
|
$this->webPush = $webPush; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Send the given notification. |
|
24
|
|
|
* |
|
25
|
|
|
* @param mixed $notifiable |
|
26
|
|
|
* @param \Illuminate\Notifications\Notification $notification |
|
27
|
|
|
* @return void |
|
28
|
|
|
*/ |
|
29
|
|
|
public function send($notifiable, Notification $notification) |
|
30
|
|
|
{ |
|
31
|
|
|
$subscriptions = $notifiable->routeNotificationFor('WebPush'); |
|
32
|
|
|
|
|
33
|
|
|
if (! $subscriptions || $subscriptions->isEmpty()) { |
|
34
|
|
|
return; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
$payload = ['notification' => $notification->toWebPush($notifiable, $notification)->toArray()]; |
|
|
|
|
|
|
38
|
|
|
$payload = json_encode($payload); |
|
39
|
|
|
|
|
40
|
|
|
$subscriptions->each(function ($sub) use ($payload) { |
|
41
|
|
|
$this->webPush->sendNotification( |
|
42
|
|
|
$sub->endpoint, |
|
43
|
|
|
$payload, |
|
44
|
|
|
$sub->public_key, |
|
45
|
|
|
$sub->auth_token |
|
46
|
|
|
); |
|
47
|
|
|
}); |
|
48
|
|
|
|
|
49
|
|
|
$response = $this->webPush->flush(); |
|
50
|
|
|
|
|
51
|
|
|
$this->deleteInvalidSubscriptions($response, $subscriptions); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* @param array|bool $response |
|
56
|
|
|
* @param \Illuminate\Database\Eloquent\Collection $subscriptions |
|
57
|
|
|
* @return void |
|
58
|
|
|
*/ |
|
59
|
|
|
protected function deleteInvalidSubscriptions($response, $subscriptions) |
|
60
|
|
|
{ |
|
61
|
|
|
if (! is_array($response)) { |
|
62
|
|
|
return; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
foreach ($response as $index => $value) { |
|
66
|
|
|
if (! $value['success'] && isset($subscriptions[$index])) { |
|
67
|
|
|
$subscriptions[$index]->delete(); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
Adding a
@returnannotation 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.