|
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\SlackableInterface; |
|
8
|
|
|
|
|
9
|
|
|
class SlackWebhookMessageAdapter extends BaseMessageAdapter implements MessageAdapterInterface |
|
10
|
|
|
{ |
|
11
|
|
|
const CHANNEL = 'slack'; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Generates a message object |
|
15
|
|
|
* |
|
16
|
|
|
* @param NotificationInterface $notification |
|
17
|
|
|
* @return \IrishDan\NotificationBundle\Message\Message |
|
18
|
|
|
*/ |
|
19
|
|
|
public function format(NotificationInterface $notification) |
|
20
|
|
|
{ |
|
21
|
|
|
$notification->setChannel(self::CHANNEL); |
|
22
|
|
|
parent::format($notification); |
|
23
|
|
|
|
|
24
|
|
|
/** @var SlackableInterface $notifiable */ |
|
25
|
|
|
$notifiable = $notification->getNotifiable(); |
|
26
|
|
|
if (!$notifiable instanceof SlackableInterface) { |
|
27
|
|
|
$this->createFormatterException(SlackableInterface::class, self::CHANNEL); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
// Build the dispatch data array. |
|
31
|
|
|
$dispatchData = [ |
|
32
|
|
|
'webhook' => $notifiable->getSlackWebhook(), |
|
33
|
|
|
]; |
|
34
|
|
|
|
|
35
|
|
|
$messageData = self::createMessagaData($notification->getDataArray()); |
|
36
|
|
|
|
|
37
|
|
|
return self::createMessage($dispatchData, $messageData, self::CHANNEL); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function dispatch(MessageInterface $message) |
|
41
|
|
|
{ |
|
42
|
|
|
// Get the dispatch and message data from the message. |
|
43
|
|
|
$dispatchData = $message->getDispatchData(); |
|
44
|
|
|
$messageData = $message->getMessageData(); |
|
45
|
|
|
|
|
46
|
|
|
// Build payload from the message data. |
|
47
|
|
|
$messageData['text'] = $messageData['body']; |
|
48
|
|
|
unset($messageData['body']); |
|
49
|
|
|
|
|
50
|
|
|
$data = 'payload=' . json_encode($messageData); |
|
51
|
|
|
|
|
52
|
|
|
$ch = curl_init(); |
|
53
|
|
|
curl_setopt($ch, CURLOPT_URL, $dispatchData['webhook']); |
|
54
|
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); |
|
55
|
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); |
|
56
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
57
|
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
|
58
|
|
|
$result = curl_exec($ch); |
|
59
|
|
|
|
|
60
|
|
|
if ($result !== 'ok') { |
|
61
|
|
|
return false; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
curl_close($ch); |
|
65
|
|
|
|
|
66
|
|
|
return true; |
|
67
|
|
|
} |
|
68
|
|
|
} |