1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NotificationChannels\Fcm; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use GuzzleHttp\Exception\RequestException; |
7
|
|
|
use Illuminate\Notifications\Notification; |
8
|
|
|
use NotificationChannels\Fcm\Exceptions\CouldNotSendNotification; |
9
|
|
|
|
10
|
|
|
class FcmChannel |
11
|
|
|
{ |
12
|
|
|
const DEFAULT_API_URL = 'https://fcm.googleapis.com'; |
13
|
|
|
const MAX_TOKEN_PER_REQUEST = 1000; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var Client |
17
|
|
|
*/ |
18
|
|
|
protected $client; |
19
|
|
|
|
20
|
|
|
public function __construct(Client $client) |
21
|
|
|
{ |
22
|
|
|
$this->client = $client; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Send the given notification. |
27
|
|
|
* |
28
|
|
|
* @param mixed $notifiable |
29
|
|
|
* @param \Illuminate\Notifications\Notification $notification |
30
|
|
|
* |
31
|
|
|
* @throws \NotificationChannels\Fcm\Exceptions\CouldNotSendNotification |
32
|
|
|
*/ |
33
|
|
|
public function send($notifiable, Notification $notification) |
34
|
|
|
{ |
35
|
|
|
// Get the token/s from the model |
36
|
|
|
$tokens = (array) $notifiable->routeNotificationForFcm(); |
37
|
|
|
|
38
|
|
|
if (empty($tokens)) { |
39
|
|
|
return; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
// Get the message from the notification class |
43
|
|
|
$message = $notification->toFcm($notifiable); |
|
|
|
|
44
|
|
|
|
45
|
|
|
if (empty($message)) { |
46
|
|
|
return; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (count($tokens) == 1) { |
50
|
|
|
// Do not use multicast if there is only one recipient |
51
|
|
|
$message->setTo($tokens[0]); |
52
|
|
|
$this->sendToFcm($message); |
53
|
|
|
} else { |
54
|
|
|
// Use multicast because there are multiple recipients |
55
|
|
|
$partialTokens = array_chunk($tokens, self::MAX_TOKEN_PER_REQUEST, false); |
56
|
|
|
foreach ($partialTokens as $tokens) { |
57
|
|
|
$message->setRegistrationIds($tokens); |
58
|
|
|
$this->sendToFcm($message); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function sendToFcm($message) { |
64
|
|
|
try { |
65
|
|
|
$this->client->request('POST', '/fcm/send', [ |
66
|
|
|
'body' => $message->toJson(), |
67
|
|
|
]); |
68
|
|
|
} catch (RequestException $requestException) { |
69
|
|
|
throw CouldNotSendNotification::serviceRespondedWithAnError($requestException); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.