Passed
Push — master ( 8a6bad...40b3d8 )
by Ehsan
03:59
created

Sender   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 185
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 95.59%

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 11
dl 0
loc 185
ccs 65
cts 68
cp 0.9559
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSlackbot() 0 4 1
A setSlackbot() 0 4 1
C send() 0 34 7
A respondToSlashCommand() 0 16 1
A respondToSlack() 0 4 1
A respondAsJSON() 0 9 2
A getResponseType() 0 10 3
A getResponseByListenerType() 0 12 3
B sendConfirmation() 0 23 4
1
<?php
2
3
namespace Botonomous;
4
5
use Botonomous\listener\EventListener;
6
use Botonomous\listener\SlashCommandListener;
7
use /* @noinspection PhpUndefinedClassInspection */
8
    GuzzleHttp\Psr7\Request;
9
10
class Sender extends AbstractSender
11
{
12
    const SLACK_RESPONSE_TYPE = 'slack';
13
    const SLASH_COMMAND_RESPONSE_TYPE = 'slashCommand';
14
    const JSON_RESPONSE_TYPE = 'json';
15
16
    private $slackbot;
17
18
    /**
19
     * Sender constructor.
20
     *
21
     * @param AbstractBot $slackbot
22
     */
23 13
    public function __construct(AbstractBot $slackbot)
24
    {
25 13
        $this->setSlackbot($slackbot);
26 13
    }
27
28
    /**
29
     * @return AbstractBot
30
     */
31 9
    public function getSlackbot(): AbstractBot
32
    {
33 9
        return $this->slackbot;
34
    }
35
36
    /**
37
     * @param AbstractBot $slackbot
38
     */
39 13
    public function setSlackbot(AbstractBot $slackbot)
40
    {
41 13
        $this->slackbot = $slackbot;
42 13
    }
43
44
    /**
45
     * Final endpoint for the response.
46
     *
47
     * @param $channel
48
     * @param $text
49
     * @param $attachments
50
     *
51
     * @throws \Exception
52
     *
53
     * @return bool
54
     */
55 9
    public function send($text, $channel = null, $attachments = null)
56
    {
57
        // @codeCoverageIgnoreStart
58
        if ($this->getSlackbot()->getListener()->isThisBot() !== false) {
59
            return false;
60
        }
61
        // @codeCoverageIgnoreEnd
62
63 9
        if (empty($channel)) {
64 3
            $channel = $this->getSlackbot()->getListener()->getChannelId();
65
        }
66
67
        $data = [
68 9
            'text'    => $text,
69 9
            'channel' => $channel,
70
        ];
71
72 9
        if ($attachments !== null) {
73 1
            $data['attachments'] = json_encode($attachments);
74
        }
75
76 9
        $this->getLoggerUtility()->logChat(__METHOD__, $text, $channel);
77
78 9
        $responseType = $this->getResponseType();
79 9
        if ($responseType === self::SLACK_RESPONSE_TYPE) {
80 1
            $this->respondToSlack($data);
81 8
        } elseif ($responseType === self::SLASH_COMMAND_RESPONSE_TYPE) {
82 1
            $this->respondToSlashCommand($text);
83 7
        } elseif ($responseType === self::JSON_RESPONSE_TYPE) {
84 7
            $this->respondAsJSON($data);
85
        }
86
87 9
        return true;
88
    }
89
90
    /**
91
     * @param $response
92
     */
93 1
    private function respondToSlashCommand($response)
94
    {
95
        /** @noinspection PhpUndefinedClassInspection */
96 1
        $request = new Request(
97 1
            'POST',
98 1
            $this->getSlackbot()->getRequest('response_url'),
99 1
            ['Content-Type' => 'application/json'],
100 1
            json_encode([
101 1
                'text'          => $response,
102 1
                'response_type' => 'in_channel',
103
            ])
104
        );
105
106
        /* @noinspection PhpUndefinedClassInspection */
107 1
        $this->getClient()->send($request);
108 1
    }
109
110
    /**
111
     * @param $data
112
     * @throws \Exception
113
     */
114 1
    private function respondToSlack($data)
115
    {
116 1
        $this->getApiClient()->chatPostMessage($data);
117 1
    }
118
119
    /**
120
     * @param $data
121
     */
122 7
    private function respondAsJSON($data)
123
    {
124
        // headers_sent is used to avoid issue in the test
125 7
        if (!headers_sent()) {
126 7
            header('Content-type:application/json;charset=utf-8');
127
        }
128
129 7
        echo json_encode($data);
130 7
    }
131
132
    /**
133
     * Specify the response type
134
     * If response in config is set to empty, it will be considered based on listener.
135
     *
136
     * @return mixed|string
137
     * @throws \Exception
138
     */
139 9
    private function getResponseType()
140
    {
141 9
        if ($this->getSlackbot()->getRequest('debug') === true
142 9
            || $this->getSlackbot()->getRequest('debug') === 'true') {
143 7
            return self::JSON_RESPONSE_TYPE;
144
        }
145
146
        // response type in the config is empty, so choose it based on listener type
147 2
        return $this->getResponseByListenerType();
148
    }
149
150
    /**
151
     * @return string
152
     * @throws \Exception
153
     */
154 2
    private function getResponseByListenerType(): string
155
    {
156 2
        $listener = $this->getConfig()->get('listener');
157
        switch ($listener) {
158 2
            case SlashCommandListener::KEY:
159 1
                return self::SLASH_COMMAND_RESPONSE_TYPE;
160 1
            case EventListener::KEY:
161 1
                return self::SLACK_RESPONSE_TYPE;
162
            default:
163
                return self::SLASH_COMMAND_RESPONSE_TYPE;
164
        }
165
    }
166
167
    /**
168
     * Send confirmation.
169
     * @throws BotonomousException
170
     */
171 1
    public function sendConfirmation()
172
    {
173
        try {
174 1
            $userId = $this->getSlackbot()->getRequest('user_id');
175
176 1
            $user = '';
177 1
            if (!empty($userId)) {
178 1
                $user = $this->getMessageUtility()->linkToUser($userId).' ';
179
            }
180
181 1
            $confirmMessage = $this->getSlackbot()->getDictionary()->getValueByKey(
182 1
                'generic-messages',
183 1
                'confirmReceivedMessage',
184 1
                ['user' => $user]
185
            );
186
187 1
            if (!empty($confirmMessage)) {
188 1
                $this->send($confirmMessage);
189
            }
190
        } catch (\Exception $e) {
191
            throw new BotonomousException('Failed to send confirmatyion: '.$e->getMessage());
192
        }
193 1
    }
194
}
195