Completed
Pull Request — master (#85)
by
unknown
01:21
created

FcmChannel::sendToFcmMulticast()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace NotificationChannels\Fcm;
4
5
use Illuminate\Contracts\Container\BindingResolutionException;
6
use Illuminate\Contracts\Events\Dispatcher;
7
use Illuminate\Notifications\Events\NotificationFailed;
8
use Illuminate\Notifications\Notification;
9
use Kreait\Firebase\Exception\MessagingException;
10
use Kreait\Firebase\Messaging\CloudMessage;
11
use Kreait\Firebase\Messaging\Message;
12
use NotificationChannels\Fcm\Exceptions\CouldNotSendNotification;
13
use ReflectionException;
14
use Throwable;
15
16
class FcmChannel
17
{
18
    const MAX_TOKEN_PER_REQUEST = 500;
19
20
    /**
21
     * @var \Illuminate\Contracts\Events\Dispatcher
22
     */
23
    protected $events;
24
25
    /**
26
     * FcmChannel constructor.
27
     *
28
     * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
29
     */
30
    public function __construct(Dispatcher $dispatcher)
31
    {
32
        $this->events = $dispatcher;
33
    }
34
35
    /**
36
     * @var string|null
37
     */
38
    protected $fcmProject = null;
39
40
    /**
41
     * Send the given notification.
42
     *
43
     * @param mixed $notifiable
44
     * @param \Illuminate\Notifications\Notification $notification
45
     *
46
     * @return array
47
     * @throws \NotificationChannels\Fcm\Exceptions\CouldNotSendNotification
48
     * @throws \Kreait\Firebase\Exception\FirebaseException
49
     */
50
    public function send($notifiable, Notification $notification)
51
    {
52
        $token = $notifiable->routeNotificationFor('fcm', $notification);
53
54
        // Get the message from the notification class
55
        $fcmMessage = $notification->toFcm($notifiable);
0 ignored issues
show
Bug introduced by
The method toFcm() does not seem to exist on object<Illuminate\Notifications\Notification>.

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.

Loading history...
56
57
        if (! $fcmMessage instanceof Message) {
58
            throw CouldNotSendNotification::invalidMessage();
59
        }
60
61
        $this->fcmProject = null;
62
        if (method_exists($notification, 'fcmProject')) {
63
            $this->fcmProject = $notification->fcmProject($notifiable, $fcmMessage);
0 ignored issues
show
Bug introduced by
The method fcmProject() does not seem to exist on object<Illuminate\Notifications\Notification>.

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.

Loading history...
64
        }
65
66
        $responses = [];
67
68
        try {
69
70
            if(empty($token) && $fcmMessage instanceof  FcmMessage){
71
72
                if($fcmMessage->getTopic() || $fcmMessage->getCondition())
73
                    $responses[] = $this->sendToFcm($fcmMessage);
74
75
            }else if(empty($token) && $fcmMessage instanceof  CloudMessage){
76
77
                if($fcmMessage->hasTarget())
78
                    $responses[] = $this->sendToFcm($fcmMessage);
79
80
            }else if(empty($token)){
81
82
                $responses = [];
83
84
            }else if (! is_array($token)) {
85
                if ($fcmMessage instanceof CloudMessage) {
86
                    $fcmMessage = $fcmMessage->withChangedTarget('token', $token);
87
                }
88
89
                if ($fcmMessage instanceof FcmMessage) {
90
                    $fcmMessage->setToken($token);
91
                }
92
93
                $responses[] = $this->sendToFcm($fcmMessage);
94
            } else {
95
                // Use multicast because there are multiple recipients
96
                $partialTokens = array_chunk($token, self::MAX_TOKEN_PER_REQUEST, false);
97
                foreach ($partialTokens as $tokens) {
98
                    $responses[] = $this->sendToFcmMulticast($fcmMessage, $tokens);
99
                }
100
            }
101
102
        } catch (MessagingException $exception) {
103
            $this->failedNotification($notifiable, $notification, $exception);
104
            throw CouldNotSendNotification::serviceRespondedWithAnError($exception);
105
        }
106
107
        return $responses;
108
    }
109
110
    /**
111
     * @return \Kreait\Firebase\Messaging
112
     */
113
    protected function messaging()
114
    {
115
        try {
116
            $messaging = app('firebase.manager')->project($this->fcmProject)->messaging();
117
        } catch (BindingResolutionException $e) {
118
            $messaging = app('firebase.messaging');
119
        } catch (ReflectionException $e) {
120
            $messaging = app('firebase.messaging');
121
        }
122
123
        return $messaging;
124
    }
125
126
    /**
127
     * @param \Kreait\Firebase\Messaging\Message $fcmMessage
128
     * @return array
129
     * @throws \Kreait\Firebase\Exception\MessagingException
130
     * @throws \Kreait\Firebase\Exception\FirebaseException
131
     */
132
    protected function sendToFcm(Message $fcmMessage)
133
    {
134
        return $this->messaging()->send($fcmMessage);
135
    }
136
137
    /**
138
     * @param $fcmMessage
139
     * @param array $tokens
140
     * @return \Kreait\Firebase\Messaging\MulticastSendReport
141
     * @throws \Kreait\Firebase\Exception\MessagingException
142
     * @throws \Kreait\Firebase\Exception\FirebaseException
143
     */
144
    protected function sendToFcmMulticast($fcmMessage, array $tokens)
145
    {
146
        return $this->messaging()->sendMulticast($fcmMessage, $tokens);
147
    }
148
149
    /**
150
     * Dispatch failed event.
151
     *
152
     * @param mixed $notifiable
153
     * @param \Illuminate\Notifications\Notification $notification
154
     * @param \Throwable $exception
155
     * @return array|null
156
     */
157
    protected function failedNotification($notifiable, Notification $notification, Throwable $exception)
158
    {
159
        return $this->events->dispatch(new NotificationFailed(
160
            $notifiable,
161
            $notification,
162
            self::class,
163
            [
164
                'message' => $exception->getMessage(),
165
                'exception' => $exception,
166
            ]
167
        ));
168
    }
169
}
170