Completed
Branch master (812a3e)
by Frank
04:30 queued 02:09
created

AbstractCommand::getBaseDataArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 2
dl 0
loc 10
ccs 8
cts 8
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * T3Bot.
4
 *
5
 * @author Frank Nägler <[email protected]>
6
 *
7
 * @link http://www.t3bot.de
8
 * @link http://wiki.typo3.org/T3Bot
9
 */
10
namespace T3Bot\Commands;
11
12
use /* @noinspection PhpInternalEntityUsedInspection */ Doctrine\DBAL\Configuration;
13
use Doctrine\DBAL\Connection;
14
use Doctrine\DBAL\DriverManager;
15
use Slack\DataObject;
16
use Slack\Message\Attachment;
17
use Slack\Payload;
18
use Slack\RealTimeClient;
19
use T3Bot\Slack\Message;
20
use T3Bot\Traits\ForgerTrait;
21
use T3Bot\Traits\GerritTrait;
22
use T3Bot\Traits\SlackTrait;
23
24
/**
25
 * Class AbstractCommand.
26
 *
27
 * @property string commandName
28
 * @property array helpCommands
29
 */
30
abstract class AbstractCommand
31
{
32
    use SlackTrait, ForgerTrait, GerritTrait;
33
34
    const PROJECT_PHASE_DEVELOPMENT = 'development';
35
    const PROJECT_PHASE_STABILISATION = 'stabilisation';
36
    const PROJECT_PHASE_SOFT_FREEZE = 'soft_freeze';
37
    const PROJECT_PHASE_CODE_FREEZE = 'code_freeze';
38
    const PROJECT_PHASE_FEATURE_FREEZE = 'feature_freeze';
39
40
    /**
41
     * @var string
42
     */
43
    protected $commandName;
44
45
    /**
46
     * @var array
47
     */
48
    protected $helpCommands = [];
49
50
    /**
51
     * @var array
52
     */
53
    protected $params = [];
54
55
    /**
56
     * @var Payload
57
     */
58
    protected $payload;
59
60
    /**
61
     * @var RealTimeClient
62
     */
63
    protected $client;
64
65
    /**
66
     * AbstractCommand constructor.
67
     *
68
     * @param Payload        $payload
69
     * @param RealTimeClient $client
70
     */
71 102
    public function __construct(Payload $payload, RealTimeClient $client)
72
    {
73 102
        $this->payload = $payload;
74 102
        $this->client = $client;
75 102
    }
76
77
    /**
78
     *
79
     */
80 46
    public function process()
81
    {
82 46
        $commandParts = explode(':', $this->payload->getData()['text']);
83 46
        $params = [];
84 46
        if (!empty($commandParts[1])) {
85 46
            array_shift($commandParts);
86 46
            $params = explode(' ', preg_replace('/\s+/', ' ', implode(':', $commandParts)));
87
        }
88
89 46
        $command = !empty($params[0]) ? $params[0] : 'help';
90 46
        $this->params = $params;
91 46
        $method = 'process' . ucfirst(strtolower($command));
92 46
        if (method_exists($this, $method)) {
93 45
            return $this->{$method}();
94
        }
95
96 1
        return $this->getHelp();
97
    }
98
99
    /**
100
     * @param Message|string $messageToSent
101
     * @param string $user
102
     * @param string $channel the channel id
103
     */
104 2
    public function sendResponse($messageToSent, $user = null, $channel = null)
105
    {
106 2
        if ($user !== null) {
107
            $this->client->apiCall('im.open', ['user' => $user])
108
                ->then(function (Payload $response) use ($messageToSent) {
109
                    $channel = $response->getData()['channel']['id'];
110 View Code Duplication
                    if ($messageToSent instanceof Message) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
111
                        $data = $this->getBaseDataArray($messageToSent->getText(), $channel);
112
                        $attachments = $messageToSent->getAttachments();
113
                        if (count($attachments)) {
114
                            $data['attachments'] = [];
115
                        }
116
                        foreach ($attachments as $attachment) {
117
                            $data['attachments'][] = $this->buildAttachment($attachment);
118
                        }
119
                        $message = new \Slack\Message\Message($this->client, $data);
120
                        $this->client->postMessage($message);
121
                    } elseif (is_string($messageToSent)) {
122
                        $data = $this->getBaseDataArray($messageToSent, $channel);
123
                        $data['as_user'] = true;
124
                        $this->client->apiCall('chat.postMessage', $data);
125
                    }
126
                });
127
        } else {
128 2
            $channel = $channel ?? $this->payload->getData()['channel'];
129 2 View Code Duplication
            if ($messageToSent instanceof Message) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130 1
                $data = $this->getBaseDataArray($messageToSent->getText(), $channel);
131 1
                $attachments = $messageToSent->getAttachments();
132 1
                if (count($attachments)) {
133 1
                    $data['attachments'] = [];
134
                }
135 1
                foreach ($attachments as $attachment) {
136 1
                    $data['attachments'][] = $this->buildAttachment($attachment);
137
                }
138 1
                $message = new \Slack\Message\Message($this->client, $data);
139 1
                $this->client->postMessage($message);
140 1
            } elseif (is_string($messageToSent)) {
141 1
                $data = $this->getBaseDataArray($messageToSent, $channel);
142 1
                $data['as_user'] = true;
143 1
                $this->client->apiCall('chat.postMessage', $data);
144
            }
145
        }
146 2
    }
147
148
    /**
149
     * generate help.
150
     *
151
     * @return string
152
     */
153 1
    public function getHelp() : string
154
    {
155 1
        $result = "*HELP*\n";
156 1
        foreach ($this->helpCommands as $command => $helpText) {
157 1
            $result .= "*{$this->commandName}:{$command}*: {$helpText} \n";
158
        }
159
160 1
        return $result;
161
    }
162
163
    /**
164
     * build a review message.
165
     *
166
     * @param \stdClass $item the review item
167
     *
168
     * @return Message
169
     */
170 12
    protected function buildReviewMessage($item) : Message
171
    {
172 12
        $created = substr($item->created, 0, 19);
173 12
        $branch = $item->branch;
174 12
        $text = '';
175
176 12
        $message = new Message();
177 12
        $attachment = new Message\Attachment();
178 12
        switch ($GLOBALS['config']['projectPhase']) {
179 12
            case self::PROJECT_PHASE_STABILISATION:
180 1
                $attachment->setColor(Message\Attachment::COLOR_WARNING);
181 1
                $attachment->setPretext(':warning: *stabilisation phase*');
182 1
                break;
183 11
            case self::PROJECT_PHASE_SOFT_FREEZE:
184 1
                $attachment->setColor(Message\Attachment::COLOR_DANGER);
185 1
                $attachment->setPretext(':no_entry: *soft merge freeze*');
186 1
                break;
187 10
            case self::PROJECT_PHASE_CODE_FREEZE:
188 1
                $attachment->setColor(Message\Attachment::COLOR_DANGER);
189 1
                $attachment->setPretext(':no_entry: *merge freeze*');
190 1
                break;
191 9
            case self::PROJECT_PHASE_FEATURE_FREEZE:
192 1
                $attachment->setColor(Message\Attachment::COLOR_DANGER);
193 1
                $attachment->setPretext(':no_entry: *FEATURE FREEZE*');
194 1
                break;
195 8
            case self::PROJECT_PHASE_DEVELOPMENT:
196
            default:
197 8
                $attachment->setColor(Message\Attachment::COLOR_NOTICE);
198 8
                break;
199
        }
200 12
        $attachment->setTitle($item->subject);
201 12
        $attachment->setTitleLink('https://review.typo3.org/' . $item->_number);
202
203 12
        $text .= 'Branch: ' . $this->bold($branch) . ' | :calendar: ' . $this->bold($created)
204 12
            . ' | ID: ' . $this->bold($item->_number) . "\n";
205 12
        $text .= '<https://review.typo3.org/' . $item->_number . '|:arrow_right: Goto Review>';
206
207 12
        $attachment->setText($text);
208 12
        $attachment->setFallback($text);
209 12
        $message->setText(' ');
210 12
        $message->addAttachment($attachment);
211
212 12
        return $message;
213
    }
214
215
    /**
216
     * @param string $text
217
     * @param string $channel
218
     *
219
     * @return array
220
     */
221 2
    protected function getBaseDataArray(string $text, string $channel) : array
222
    {
223 2
        $data = [];
224 2
        $data['unfurl_links'] = false;
225 2
        $data['unfurl_media'] = false;
226 2
        $data['parse'] = 'none';
227 2
        $data['text'] = $text;
228 2
        $data['channel'] = $channel;
229 2
        return $data;
230
    }
231
232
    /**
233
     * @param Message\Attachment $attachment
234
     *
235
     * @return DataObject
236
     */
237 1
    protected function buildAttachment(Message\Attachment $attachment) : DataObject
238
    {
239 1
        return Attachment::fromData([
240 1
            'title' => $attachment->getTitle(),
241 1
            'title_link' => $attachment->getTitleLink(),
242 1
            'text' => $attachment->getText(),
243 1
            'fallback' => $attachment->getFallback(),
244 1
            'color' => $attachment->getColor(),
245 1
            'pretext' => $attachment->getPretext(),
246 1
            'author_name' => $attachment->getAuthorName(),
247 1
            'author_icon' => $attachment->getAuthorIcon(),
248 1
            'author_link' => $attachment->getAuthorLink(),
249 1
            'image_url' => $attachment->getImageUrl(),
250 1
            'thumb_url' => $attachment->getThumbUrl(),
251
        ]);
252
    }
253
254
    /**
255
     * @return Connection
256
     *
257
     * @throws \Doctrine\DBAL\DBALException
258
     */
259 11
    protected function getDatabaseConnection() : Connection
260
    {
261 11
        if (empty($GLOBALS['DB'])) {
262 11
            $config = new Configuration();
263 11
            $GLOBALS['DB'] = DriverManager::getConnection($GLOBALS['config']['db'], $config);
264
        }
265
266 11
        return $GLOBALS['DB'];
267
    }
268
}
269