SlackWebhookMessageAdapter   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 4
dl 0
loc 58
rs 10
c 0
b 0
f 0

2 Methods

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