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
|
3 |
|
public function __construct(WebPush $webPush) |
18
|
|
|
{ |
19
|
3 |
|
$this->webPush = $webPush; |
20
|
3 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Send the given notification. |
24
|
|
|
* |
25
|
|
|
* @param mixed $notifiable |
26
|
|
|
* @param \Illuminate\Notifications\Notification $notification |
27
|
|
|
* @return void |
28
|
|
|
*/ |
29
|
3 |
|
public function send($notifiable, Notification $notification) |
30
|
|
|
{ |
31
|
3 |
|
$subscriptions = $notifiable->routeNotificationFor('WebPush'); |
32
|
|
|
|
33
|
3 |
|
if (! $subscriptions || $subscriptions->isEmpty()) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
3 |
|
$webPushMessage = $notification->toWebPush($notifiable, $notification); |
|
|
|
|
38
|
3 |
|
$webPushMessageArr = $webPushMessage->toArray(); |
39
|
|
|
|
40
|
3 |
|
$options = []; |
41
|
3 |
|
if(isset($webPushMessageArr['options'])) { |
42
|
1 |
|
$options = $webPushMessageArr['options']; |
43
|
1 |
|
unset($webPushMessageArr['options']); |
44
|
|
|
} |
45
|
|
|
|
46
|
3 |
|
$payload = json_encode($webPushMessageArr); |
47
|
|
|
|
48
|
3 |
|
$subscriptions->each(function ($sub) use ($payload, $options) { |
49
|
3 |
|
$this->webPush->sendNotification( |
50
|
3 |
|
$sub->endpoint, |
51
|
3 |
|
$payload, |
52
|
3 |
|
$sub->public_key, |
53
|
3 |
|
$sub->auth_token, |
54
|
3 |
|
$options |
55
|
|
|
); |
56
|
3 |
|
}); |
57
|
|
|
|
58
|
3 |
|
$response = $this->webPush->flush(); |
59
|
|
|
|
60
|
3 |
|
$this->deleteInvalidSubscriptions($response, $subscriptions); |
61
|
3 |
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param array|bool $response |
65
|
|
|
* @param \Illuminate\Database\Eloquent\Collection $subscriptions |
66
|
|
|
* @return void |
67
|
|
|
*/ |
68
|
3 |
|
protected function deleteInvalidSubscriptions($response, $subscriptions) |
69
|
|
|
{ |
70
|
3 |
|
if (! is_array($response)) { |
71
|
2 |
|
return; |
72
|
|
|
} |
73
|
|
|
|
74
|
1 |
|
foreach ($response as $index => $value) { |
75
|
1 |
|
if (! $value['success'] && isset($subscriptions[$index])) { |
76
|
1 |
|
$subscriptions[$index]->delete(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
1 |
|
} |
80
|
|
|
} |
81
|
|
|
|
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.