Sender   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 189
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 189
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
B 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
A 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
     *
113
     * @throws \Exception
114
     */
115 1
    private function respondToSlack($data)
116
    {
117 1
        $this->getApiClient()->chatPostMessage($data);
118 1
    }
119
120
    /**
121
     * @param $data
122
     */
123 7
    private function respondAsJSON($data)
124
    {
125
        // headers_sent is used to avoid issue in the test
126 7
        if (!headers_sent()) {
127 7
            header('Content-type:application/json;charset=utf-8');
128
        }
129
130 7
        echo json_encode($data);
131 7
    }
132
133
    /**
134
     * Specify the response type
135
     * If response in config is set to empty, it will be considered based on listener.
136
     *
137
     * @throws \Exception
138
     *
139
     * @return mixed|string
140
     */
141 9
    private function getResponseType()
142
    {
143 9
        if ($this->getSlackbot()->getRequest('debug') === true
144 9
            || $this->getSlackbot()->getRequest('debug') === 'true') {
145 7
            return self::JSON_RESPONSE_TYPE;
146
        }
147
148
        // response type in the config is empty, so choose it based on listener type
149 2
        return $this->getResponseByListenerType();
150
    }
151
152
    /**
153
     * @throws \Exception
154
     *
155
     * @return string
156
     */
157 2
    private function getResponseByListenerType(): string
158
    {
159 2
        $listener = $this->getConfig()->get('listener');
160
        switch ($listener) {
161 2
            case SlashCommandListener::KEY:
162 1
                return self::SLASH_COMMAND_RESPONSE_TYPE;
163 1
            case EventListener::KEY:
164 1
                return self::SLACK_RESPONSE_TYPE;
165
            default:
166
                return self::SLASH_COMMAND_RESPONSE_TYPE;
167
        }
168
    }
169
170
    /**
171
     * Send confirmation.
172
     *
173
     * @throws BotonomousException
174
     */
175 1
    public function sendConfirmation()
176
    {
177
        try {
178 1
            $userId = $this->getSlackbot()->getRequest('user_id');
179
180 1
            $user = '';
181 1
            if (!empty($userId)) {
182 1
                $user = $this->getMessageUtility()->linkToUser($userId).' ';
183
            }
184
185 1
            $confirmMessage = $this->getSlackbot()->getDictionary()->getValueByKey(
186 1
                'generic-messages',
187 1
                'confirmReceivedMessage',
188 1
                ['user' => $user]
189
            );
190
191 1
            if (!empty($confirmMessage)) {
192 1
                $this->send($confirmMessage);
193
            }
194
        } catch (\Exception $e) {
195
            throw new BotonomousException('Failed to send confirmatyion: '.$e->getMessage());
196
        }
197 1
    }
198
}
199