1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Webelightdev\LaravelPushNotification\Adapters; |
4
|
|
|
|
5
|
|
|
use Webelightdev\LaravelPushNotification\Facades\LogNotification; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Firebase Cloud Messaging Adapter. |
9
|
|
|
*/ |
10
|
|
|
class Fcm |
11
|
|
|
{ |
12
|
|
|
protected $url; |
13
|
|
|
protected $authKey; |
14
|
|
|
|
15
|
|
|
public function __construct() |
16
|
|
|
{ |
17
|
|
|
$this->url = config('push-notification.services.fcm.url'); |
18
|
|
|
$this->authKey = config('push-notification.services.fcm.auth_key'); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function pushNotification($deviceTokens, $message, $action) |
22
|
|
|
{ |
23
|
|
|
foreach ($deviceTokens as $deviceToken) { |
24
|
|
|
$response = $this->callService($deviceToken, $message, $action); |
25
|
|
|
$this->logResponse($response, $deviceToken, $message, $action); |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function callService($deviceToken, $message, $action) |
30
|
|
|
{ |
31
|
|
|
return file_get_contents($this->url, false, $this->setStream($deviceToken, $message, $action)); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function setStream($deviceToken, $message, $action) |
35
|
|
|
{ |
36
|
|
|
$postData['to'] = $deviceToken; |
|
|
|
|
37
|
|
|
$postData['data']['message'] = $message; |
38
|
|
|
$postData['data']['click_action'] = $action; |
39
|
|
|
|
40
|
|
|
$streamOptions = [ |
41
|
|
|
'http' => [ |
42
|
|
|
'method' => 'POST', |
43
|
|
|
'header' => "Authorization: key={$this->authKey}\r\n"."Content-Type: application/json\r\n", |
44
|
|
|
'content' => json_encode($postData), |
45
|
|
|
], |
46
|
|
|
]; |
47
|
|
|
|
48
|
|
|
return stream_context_create($streamOptions); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param string $data |
53
|
|
|
*/ |
54
|
|
|
public function logResponse($data, $deviceToken, $message, $action) |
|
|
|
|
55
|
|
|
{ |
56
|
|
|
$response = json_decode($data); |
57
|
|
|
if ($response->failure == 1) { |
58
|
|
|
LogNotification::error($deviceToken, $message, $response->results[0]->error); |
59
|
|
|
} else { |
60
|
|
|
LogNotification::info($deviceToken, $message); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArray
is initialized the first time when the foreach loop is entered. You can also see that the value of thebar
key is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.