1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace IrishDan\NotificationBundle\Adapter; |
4
|
|
|
|
5
|
|
|
use IrishDan\NotificationBundle\Message\MessageInterface; |
6
|
|
|
use IrishDan\NotificationBundle\Notification\NotificationInterface; |
7
|
|
|
use IrishDan\NotificationBundle\TextableInterface; |
8
|
|
|
use Nexmo\Client; |
9
|
|
|
|
10
|
|
|
class NexmoMessageAdapter extends BaseMessageAdapter implements MessageAdapterInterface |
11
|
|
|
{ |
12
|
|
|
const CHANNEL = 'nexmo'; |
13
|
|
|
protected $nexmoConfiguration; |
14
|
|
|
protected $client; |
15
|
|
|
|
16
|
|
|
public function __construct(array $nexmoConfiguration = []) |
17
|
|
|
{ |
18
|
|
|
$this->nexmoConfiguration = $nexmoConfiguration; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Generates a message object |
23
|
|
|
* |
24
|
|
|
* @param NotificationInterface $notification |
25
|
|
|
* @return \IrishDan\NotificationBundle\Message\Message |
26
|
|
|
*/ |
27
|
|
|
public function format(NotificationInterface $notification) |
28
|
|
|
{ |
29
|
|
|
$notification->setChannel(self::CHANNEL); |
30
|
|
|
parent::format($notification); |
31
|
|
|
|
32
|
|
|
/** @var TextableInterface $notifiable */ |
33
|
|
|
$notifiable = $notification->getNotifiable(); |
34
|
|
|
if (!$notifiable instanceof TextableInterface) { |
35
|
|
|
$this->createFormatterException(TextableInterface::class, self::CHANNEL); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
// Build the dispatch data array. |
39
|
|
|
$dispatchData = [ |
40
|
|
|
'to' => $notifiable->getNumber(), |
41
|
|
|
'from' => empty($this->nexmoConfiguration['from']) ? '' : $this->nexmoConfiguration['from'], |
42
|
|
|
]; |
43
|
|
|
|
44
|
|
|
$messageData = self::createMessagaData($notification->getDataArray()); |
45
|
|
|
|
46
|
|
|
return self::createMessage($dispatchData, $messageData, self::CHANNEL); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function dispatch(MessageInterface $message) |
50
|
|
|
{ |
51
|
|
|
// Get the dispatch and message data from the message. |
52
|
|
|
$dispatchData = $message->getDispatchData(); |
53
|
|
|
$messageData = $message->getMessageData(); |
54
|
|
|
|
55
|
|
|
if (empty($this->client)) { |
56
|
|
|
$credentials = new Client\Credentials\Basic( |
57
|
|
|
$this->nexmoConfiguration['api_key'], |
58
|
|
|
$this->nexmoConfiguration['api_secret'] |
59
|
|
|
); |
60
|
|
|
$this->client = new Client($credentials); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$sent = $this->client->message()->send( |
64
|
|
|
[ |
65
|
|
|
'to' => $dispatchData['to'], |
66
|
|
|
'from' => $dispatchData['from'], |
67
|
|
|
'text' => $messageData['body'], |
68
|
|
|
] |
69
|
|
|
); |
70
|
|
|
|
71
|
|
|
return !empty($sent); |
72
|
|
|
} |
73
|
|
|
} |