1 | <?php |
||
2 | |||
3 | namespace NotificationChannels\SmsRu; |
||
4 | |||
5 | use Illuminate\Events\Dispatcher; |
||
6 | use Illuminate\Notifications\Events\NotificationFailed; |
||
7 | use NotificationChannels\SmsRu\Exceptions\CouldNotSendNotification; |
||
8 | use Illuminate\Notifications\Notification; |
||
9 | |||
10 | class SmsRuChannel |
||
11 | { |
||
12 | /** |
||
13 | * @var SmsRuApi |
||
14 | */ |
||
15 | protected $smsApi; |
||
16 | |||
17 | /** |
||
18 | * @var Dispatcher |
||
19 | */ |
||
20 | protected $events; |
||
21 | |||
22 | /** |
||
23 | * SmsRuChannel constructor. |
||
24 | * @param SmsRuApi $smsApi |
||
25 | * @param Dispatcher $events |
||
26 | */ |
||
27 | public function __construct(SmsRuApi $smsApi, Dispatcher $events) |
||
28 | { |
||
29 | $this->smsApi = $smsApi; |
||
30 | $this->events = $events; |
||
31 | } |
||
32 | /** |
||
33 | * Send the given notification. |
||
34 | * |
||
35 | * @param mixed $notifiable |
||
36 | * @param Notification $notification |
||
37 | * |
||
38 | * @throws CouldNotSendNotification |
||
39 | * |
||
40 | * @return array|null |
||
41 | */ |
||
42 | public function send($notifiable, Notification $notification) |
||
43 | { |
||
44 | try { |
||
45 | $recipient = $this->getRecipient($notifiable); |
||
46 | $message = $notification->toSmsru($notifiable); |
||
47 | |||
48 | if (is_string($message)) { |
||
49 | $message = new SmsRuMessage($message); |
||
50 | } |
||
51 | if (! $message instanceof SmsRuMessage) { |
||
52 | throw CouldNotSendNotification::invalidMessageObject($message); |
||
53 | } |
||
54 | |||
55 | return $this->smsApi->sendMessage($recipient, $message); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
56 | |||
57 | } catch (Exception $exception) { |
||
58 | $event = new NotificationFailed($notifiable, $notification, 'smsru', ['message' => $exception->getMessage(), 'exception' => $exception]); |
||
59 | |||
60 | if (function_exists('event')) { // Use event helper when possible to add Lumen support |
||
61 | event($event); |
||
62 | } else { |
||
63 | $this->events->fire($event); |
||
64 | } |
||
65 | } |
||
66 | } |
||
67 | |||
68 | protected function getRecipient($notifiable) |
||
69 | { |
||
70 | if ($notifiable->routeNotificationFor('smsru')) { |
||
71 | return $notifiable->routeNotificationFor('smsru'); |
||
72 | } |
||
73 | |||
74 | if (isset($notifiable->phone)) { |
||
75 | return $notifiable->phone; |
||
76 | } |
||
77 | |||
78 | throw CouldNotSendNotification::invalidReceiver(); |
||
79 | } |
||
80 | } |
||
81 |