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
|
1 |
|
public function __construct(WebPush $webPush) |
18
|
|
|
{ |
19
|
1 |
|
$this->webPush = $webPush; |
20
|
1 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Send the given notification. |
24
|
|
|
* |
25
|
|
|
* @param mixed $notifiable |
26
|
|
|
* @param \Illuminate\Notifications\Notification $notification |
27
|
|
|
* @return void |
28
|
|
|
*/ |
29
|
1 |
|
public function send($notifiable, Notification $notification) |
30
|
|
|
{ |
31
|
1 |
|
$subscriptions = $notifiable->routeNotificationFor('WebPush'); |
32
|
|
|
|
33
|
1 |
|
if (! $subscriptions || $subscriptions->isEmpty()) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
$payload = json_encode($notification->toWebPush($notifiable, $notification)->toArray()); |
|
|
|
|
38
|
|
|
|
39
|
1 |
|
$subscriptions->each(function ($sub) use ($payload) { |
40
|
1 |
|
$this->webPush->sendNotification( |
41
|
1 |
|
$sub->endpoint, |
42
|
1 |
|
$payload, |
43
|
1 |
|
$sub->public_key, |
44
|
1 |
|
$sub->auth_token |
45
|
|
|
); |
46
|
1 |
|
}); |
47
|
|
|
|
48
|
1 |
|
$response = $this->webPush->flush(); |
49
|
1 |
|
$this->deleteInvalidSubscriptions($response, $subscriptions); |
50
|
1 |
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param array|bool $response |
54
|
|
|
* @param \Illuminate\Database\Eloquent\Collection $subscriptions |
55
|
|
|
* @return void |
56
|
|
|
*/ |
57
|
1 |
|
protected function deleteInvalidSubscriptions($response, $subscriptions) |
58
|
|
|
{ |
59
|
1 |
|
if (!is_array($response)) { |
60
|
1 |
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
foreach ($response as $index => $value) { |
64
|
|
|
list( |
65
|
|
|
'success' => $success, |
66
|
|
|
'statusCode' => $status |
67
|
|
|
) = $value; |
68
|
|
|
|
69
|
|
|
// Continue when the request was successful |
70
|
|
|
if ($success) { |
71
|
|
|
continue; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
// Remove subscription if the server responded with a 404 or 410 code |
75
|
|
|
// https://developers.google.com/web/fundamentals/push-notifications/common-issues-and-reporting-bugs#http_status_codes |
76
|
|
|
if (in_array($status, [404, 410])) { |
77
|
|
|
$subsciption = $subscriptions[$index]; |
78
|
|
|
$subsciption->delete(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
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.