1 | <?php |
||
2 | |||
3 | namespace NotificationChannels\AfricasTalking; |
||
4 | |||
5 | use AfricasTalking\SDK\AfricasTalking as AfricasTalkingSDK; |
||
6 | use Exception; |
||
7 | use Illuminate\Notifications\Notification; |
||
8 | use NotificationChannels\AfricasTalking\Exceptions\CouldNotSendNotification; |
||
9 | use NotificationChannels\AfricasTalking\Exceptions\InvalidPhonenumber; |
||
10 | |||
11 | class AfricasTalkingChannel |
||
12 | { |
||
13 | /** @var AfricasTalkingSDK */ |
||
14 | protected $africasTalking; |
||
15 | |||
16 | 2 | /** @param AfricasTalkingSDK $africasTalking */ |
|
17 | public function __construct(AfricasTalkingSDK $africasTalking) |
||
18 | 2 | { |
|
19 | 2 | $this->africasTalking = $africasTalking; |
|
20 | } |
||
21 | |||
22 | /** |
||
23 | * Send the given notification. |
||
24 | * |
||
25 | * @param mixed $notifiable |
||
26 | * @param \Illuminate\Notifications\Notification $notification |
||
27 | * |
||
28 | 1 | * @throws CouldNotSendNotification |
|
29 | */ |
||
30 | 1 | public function send($notifiable, Notification $notification) |
|
31 | { |
||
32 | 1 | $message = $notification->toAfricasTalking($notifiable); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
33 | |||
34 | $phoneNumber = $this->getTo($notifiable, $notification, $message); |
||
35 | |||
36 | if (empty($phoneNumber)) { |
||
37 | 1 | throw InvalidPhonenumber::configurationNotSet(); |
|
38 | 1 | } |
|
39 | 1 | ||
40 | 1 | if (empty(($message->getSender())) || is_null($message->getSender())) { |
|
41 | $params = [ |
||
42 | 'to' => $phoneNumber, |
||
43 | 'message' => $message->getContent(), |
||
44 | ]; |
||
45 | 1 | } else { |
|
46 | $params = [ |
||
47 | 'to' => $phoneNumber, |
||
48 | 'message' => $message->getContent(), |
||
49 | 'from' => $message->getSender(), |
||
50 | ]; |
||
51 | } |
||
52 | |||
53 | try { |
||
54 | return $this->africasTalking->sms()->send($params); |
||
55 | } catch (Exception $e) { |
||
56 | throw CouldNotSendNotification::serviceRespondedWithAnError($e->getMessage()); |
||
57 | } |
||
58 | } |
||
59 | |||
60 | private function getTo($notifiable, Notification $notification, AfricasTalkingMessage $message) |
||
61 | { |
||
62 | if (! empty($message->getTo())) { |
||
63 | return $message->getTo(); |
||
64 | } |
||
65 | |||
66 | if ($notifiable->routeNotificationFor(static::class, $notification)) { |
||
67 | return $notifiable->routeNotificationFor(static::class, $notification); |
||
68 | } |
||
69 | |||
70 | if ($notifiable->routeNotificationFor('africasTalking', $notification)) { |
||
71 | return $notifiable->routeNotificationFor('africasTalking', $notification); |
||
72 | } |
||
73 | |||
74 | if (isset($notifiable->phone_number)) { |
||
75 | return $notifiable->phone_number; |
||
76 | } |
||
77 | |||
78 | throw CouldNotSendNotification::invalidReceiver(); |
||
79 | } |
||
80 | } |
||
81 |