1 | <?php |
||
11 | class TwilioChannel |
||
12 | { |
||
13 | /** |
||
14 | * @var Twilio |
||
15 | */ |
||
16 | protected $twilio; |
||
17 | |||
18 | /** |
||
19 | * @var Dispatcher |
||
20 | */ |
||
21 | protected $events; |
||
22 | |||
23 | /** |
||
24 | * TwilioChannel constructor. |
||
25 | * |
||
26 | * @param Twilio $twilio |
||
27 | * @param Dispatcher $events |
||
28 | */ |
||
29 | public function __construct(Twilio $twilio, Dispatcher $events) |
||
30 | { |
||
31 | $this->twilio = $twilio; |
||
32 | $this->events = $events; |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * Send the given notification. |
||
37 | * |
||
38 | * @param mixed $notifiable |
||
39 | * @param \Illuminate\Notifications\Notification $notification |
||
40 | * @return mixed |
||
41 | * @throws CouldNotSendNotification |
||
42 | */ |
||
43 | public function send($notifiable, Notification $notification) |
||
44 | { |
||
45 | try { |
||
46 | $to = $this->getTo($notifiable); |
||
47 | $message = $notification->toTwilio($notifiable); |
||
48 | $useSender = $this->canReceiveAlphanumericSender($notifiable); |
||
49 | |||
50 | if (is_string($message)) { |
||
51 | $message = new TwilioSmsMessage($message); |
||
52 | } |
||
53 | |||
54 | if (! $message instanceof TwilioMessage) { |
||
55 | throw CouldNotSendNotification::invalidMessageObject($message); |
||
56 | } |
||
57 | |||
58 | return $this->twilio->sendMessage($message, $to, $useSender); |
||
59 | } catch (Exception $exception) { |
||
60 | $event = new NotificationFailed($notifiable, $notification, 'twilio', ['message' => $exception->getMessage(), 'exception' => $exception]); |
||
61 | if (function_exists('event')) { // Use event helper when possible to add Lumen support |
||
62 | event($event); |
||
63 | } else { |
||
64 | $this->events->fire($event); |
||
65 | } |
||
66 | |||
67 | // Rethrow exception so that job status is handled |
||
68 | throw $exception |
||
69 | } |
||
|
|||
70 | } |
||
71 | |||
72 | /** |
||
73 | * Get the address to send a notification to. |
||
74 | * |
||
75 | * @param mixed $notifiable |
||
76 | * @return mixed |
||
77 | * @throws CouldNotSendNotification |
||
78 | */ |
||
79 | protected function getTo($notifiable) |
||
80 | { |
||
81 | if ($notifiable->routeNotificationFor('twilio')) { |
||
82 | return $notifiable->routeNotificationFor('twilio'); |
||
83 | } |
||
84 | if (isset($notifiable->phone_number)) { |
||
85 | return $notifiable->phone_number; |
||
86 | } |
||
87 | |||
88 | throw CouldNotSendNotification::invalidReceiver(); |
||
89 | } |
||
90 | |||
91 | /** |
||
92 | * Get the alphanumeric sender. |
||
93 | * |
||
94 | * @param $notifiable |
||
95 | * @return mixed|null |
||
96 | * @throws CouldNotSendNotification |
||
97 | */ |
||
98 | protected function canReceiveAlphanumericSender($notifiable) |
||
99 | { |
||
100 | return method_exists($notifiable, 'canReceiveAlphanumericSender') && |
||
101 | $notifiable->canReceiveAlphanumericSender(); |
||
104 |