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->isEmpty()) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$payload = json_encode($notification->toWebPush($notifiable, $notification)->toArray()); |
|
|
|
|
38
|
|
|
|
39
|
|
|
$subscriptions->each(function ($sub) use ($payload) { |
40
|
|
|
$this->webPush->sendNotification( |
41
|
|
|
$sub->endpoint, |
42
|
|
|
$payload, |
43
|
|
|
$sub->public_key, |
44
|
|
|
$sub->auth_token |
45
|
|
|
); |
46
|
|
|
}); |
47
|
|
|
|
48
|
|
|
$response = $this->webPush->flush(); |
49
|
|
|
|
50
|
|
|
$this->deleteInvalidSubscriptions($response, $subscriptions); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param array|bool $response |
55
|
|
|
* @param \Illuminate\Database\Eloquent\Collection $subscriptions |
56
|
|
|
*/ |
57
|
|
|
protected function deleteInvalidSubscriptions($response, $subscriptions) |
58
|
|
|
{ |
59
|
|
|
if (! is_array($response)) { |
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
foreach ($response as $index => $value) { |
64
|
|
|
if (! $value['success'] && isset($subscriptions[$index])) { |
65
|
|
|
$subscriptions[$index]->delete(); |
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.