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

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