1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NotificationChannels\Twilio; |
4
|
|
|
|
5
|
|
|
use NotificationChannels\Twilio\Exceptions\CouldNotSendNotification; |
6
|
|
|
use Services_Twilio as TwilioService; |
7
|
|
|
|
8
|
|
|
class Twilio |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var TwilioService |
12
|
|
|
*/ |
13
|
|
|
protected $twilioService; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Default 'from' from config. |
17
|
|
|
* @var string |
18
|
|
|
*/ |
19
|
|
|
protected $from; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Twilio constructor. |
23
|
|
|
* |
24
|
|
|
* @param TwilioService $twilioService |
25
|
|
|
* @param string $from |
26
|
|
|
*/ |
27
|
7 |
|
public function __construct(TwilioService $twilioService, $from) |
28
|
|
|
{ |
29
|
7 |
|
$this->twilioService = $twilioService; |
30
|
7 |
|
$this->from = $from; |
31
|
7 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Send a TwilioMessage to the a phone number. |
35
|
|
|
* |
36
|
|
|
* @param TwilioMessage $message |
37
|
|
|
* @param $to |
38
|
|
|
* @return mixed |
39
|
|
|
* @throws CouldNotSendNotification |
40
|
|
|
*/ |
41
|
6 |
|
public function sendMessage(TwilioMessage $message, $to) |
42
|
|
|
{ |
43
|
6 |
|
if ($message instanceof TwilioSmsMessage) { |
44
|
3 |
|
return $this->sendSmsMessage($message, $to); |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
if ($message instanceof TwilioCallMessage) { |
48
|
2 |
|
return $this->makeCall($message, $to); |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
throw CouldNotSendNotification::invalidMessageObject($message); |
52
|
|
|
} |
53
|
|
|
|
54
|
3 |
|
protected function sendSmsMessage($message, $to) |
55
|
|
|
{ |
56
|
3 |
|
return $this->twilioService->account->messages->sendMessage( |
57
|
3 |
|
$this->getFrom($message), |
58
|
|
|
$to, |
59
|
2 |
|
trim($message->content) |
60
|
|
|
); |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
protected function makeCall($message, $to) |
64
|
|
|
{ |
65
|
2 |
|
return $this->twilioService->account->calls->create( |
66
|
2 |
|
$this->getFrom($message), |
67
|
|
|
$to, |
68
|
2 |
|
trim($message->content) |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
|
72
|
5 |
|
protected function getFrom($message) |
73
|
|
|
{ |
74
|
5 |
|
if (! $from = $message->from ?: $this->from) { |
75
|
1 |
|
throw CouldNotSendNotification::missingFrom(); |
76
|
|
|
} |
77
|
|
|
|
78
|
4 |
|
return $from; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|