Passed
Push — master ( 012c32...be25cd )
by Zing
05:07
created

SmsChannel::send()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
nc 5
nop 2
dl 0
loc 15
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
namespace Zing\LaravelSms\Channels;
4
5
use Illuminate\Notifications\AnonymousNotifiable;
6
use Illuminate\Notifications\Notification;
7
use Zing\LaravelSms\Message;
8
use Zing\LaravelSms\SmsManager;
9
10
/**
11
 * Class SmsChannel.
12
 */
13
class SmsChannel
14
{
15
    protected $smsManager;
16
17
    /**
18
     * Create a new database channel.
19
     *
20
     * @param \Zing\LaravelSms\SmsManager $smsManager
21
     */
22
    public function __construct(SmsManager $smsManager)
23
    {
24
        $this->smsManager = $smsManager;
25
    }
26
27
    /**
28
     * Send the given notification.
29
     *
30
     * @param mixed $notifiable
31
     * @param \Illuminate\Notifications\Notification $notification
32
     *
33
     * @return void
34
     */
35
    public function send($notifiable, Notification $notification)
36
    {
37
        $message = $this->getData($notifiable, $notification);
38
        $receiver = $this->resolveReceiver($notifiable, $notification);
39
        if (! $receiver) {
40
            return;
41
        }
42
        if (is_string($message)) {
43
            $message = Message::text($message);
44
        }
45
        if (! $message instanceof Message) {
46
            return;
47
        }
48
49
        return $this->smsManager->connection($message->connection)->send($receiver, $message);
50
    }
51
52
    public function resolveReceiver($notifiable, Notification $notification)
53
    {
54
        if ($notifiable instanceof AnonymousNotifiable) {
55
            $receiver = $notifiable->routeNotificationFor(static::class);
56
            if ($receiver) {
57
                return $receiver;
58
            }
59
60
            return $notifiable->routeNotificationFor('sms');
61
        }
62
63
        return $notifiable->routeNotificationFor('sms', $notification);
64
    }
65
66
    /**
67
     * Get the data for the notification.
68
     *
69
     * @param  mixed  $notifiable
70
     * @param  \Illuminate\Notifications\Notification  $notification
71
     *
72
     * @return mixed
73
     *
74
     * @throws \RuntimeException
75
     */
76
    protected function getData($notifiable, Notification $notification)
77
    {
78
        if (method_exists($notification, 'toSms')) {
79
            return $notification->toSms($notifiable);
80
        }
81
82
        throw new \RuntimeException('Notification is missing toSms method.');
83
    }
84
}
85