Passed
Pull Request — master (#15)
by
unknown
05:36
created

SlackBot   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 133
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 35%

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 4
dl 0
loc 133
ccs 14
cts 40
cp 0.35
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getConfig() 0 4 1
A setConfig() 0 4 1
A quoteTypeColor() 0 8 2
A sendMessage() 0 4 1
B buildPostBody() 0 35 8
A sendRequest() 0 9 2
1
<?php
2
/**
3
 * This file is part of the WoW-Apps/Symfony-Slack-Bot bundle for Symfony 3
4
 * https://github.com/wow-apps/symfony-slack-bot
5
 *
6
 * (c) 2016 WoW-Apps
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WowApps\SlackBundle\Service;
13
14
use GuzzleHttp\Client as GuzzleClient;
15
use Symfony\Component\HttpFoundation\Response;
16
use WowApps\SlackBundle\DTO\SlackMessage;
17
18
/**
19
 * @author Alexey Samara <[email protected]>
20
 * @package WowApps\SlackBundle
21
 * @see https://github.com/wow-apps/symfony-slack-bot/wiki/2.-Using-SlackBot
22
 */
23
class SlackBot
24
{
25
    const QUOTE_DEFAULT   = 0;
26
    const QUOTE_DANGER    = 1;
27
    const QUOTE_SUCCESS   = 2;
28
    const QUOTE_WARNING   = 3;
29
    const QUOTE_INFO      = 4;
30
    const QUOTE_MAP       = [
31
        self::QUOTE_DEFAULT  => 'default',
32
        self::QUOTE_DANGER   => 'danger',
33
        self::QUOTE_SUCCESS  => 'success',
34
        self::QUOTE_WARNING  => 'warning',
35
        self::QUOTE_INFO     => 'info'
36
    ];
37
38
    const ALLOWED_RESPONSE_STATUSES = [
39
        Response::HTTP_OK,
40
        Response::HTTP_MOVED_PERMANENTLY,
41
        Response::HTTP_FOUND
42
    ];
43
44
    /** @var array */
45
    private $config;
46
47
    /** @var GuzzleClient */
48
    private $guzzleClient;
49
50
    /** @var SlackMessageValidator */
51
    private $validator;
52
53
    /**
54
     * @param array $config
55
     * @param SlackMessageValidator $validator
56
     */
57 3
    public function __construct(array $config, SlackMessageValidator $validator)
58
    {
59 3
        $this->setConfig($config);
60 3
        $this->guzzleClient = new GuzzleClient();
61 3
        $this->validator = $validator;
62 3
    }
63
64
    /**
65
     * @return array
66
     */
67 2
    public function getConfig(): array
68
    {
69 2
        return $this->config;
70
    }
71
72
    /**
73
     * @param array $config
74
     */
75 3
    public function setConfig(array $config)
76
    {
77 3
        $this->config = $config;
78 3
    }
79
80
    /**
81
     * @param int $quoteType
82
     * @return string
83
     */
84 1
    public function quoteTypeColor(int $quoteType): string
85
    {
86 1
        if (!array_key_exists($quoteType, self::QUOTE_MAP)) {
87 1
            throw new \InvalidArgumentException('Unknown quote type');
88
        }
89
90 1
        return $this->config['quote_color'][self::QUOTE_MAP[$quoteType]];
91
    }
92
93
    /**
94
     * @param SlackMessage $slackMessage
95
     * @return bool
96
     */
97
    public function sendMessage(SlackMessage $slackMessage): bool
98
    {
99
        return $this->sendRequest($this->buildPostBody($slackMessage));
100
    }
101
102
    /**
103
     * @param SlackMessage $slackMessage
104
     * @return string
105
     */
106
    private function buildPostBody(SlackMessage $slackMessage): string
107
    {
108
        $this->validator->validateMessage($slackMessage);
109
        $slackMessage = $this->validator->setDefaultsForEmptyFields($slackMessage, $this->getConfig());
110
111
        $return = [
112
            'text' => $slackMessage->getText(),
113
            'channel' => $slackMessage->getRecipient(),
114
            'username' => $slackMessage->getSender(),
115
            'mrkdwn' => true,
116
            'as_user' => false
117
        ];
118
119
        if (!empty($slackMessage->getIconUrl())) {
120
            $return['icon_url'] = $slackMessage->getIconUrl();
121
        }
122
123
        if (empty($slackMessage->getIconUrl()) && !empty($slackMessage->getIconEmoji())) {
124
            $this->validator->validateIconEmoji($slackMessage);
125
            $return['icon_emoji'] = $slackMessage->getIconEmoji();
126
        }
127
128
        if ($slackMessage->isShowQuote()) {
129
            $return['attachments'][] = [
130
                'fallback' => $slackMessage->getText(),
131
                'title' => (!$slackMessage->getQuoteTitle() ? '' : $slackMessage->getQuoteTitle()),
132
                'title_link' => (!$slackMessage->getQuoteTitleLink() ? '' : $slackMessage->getQuoteTitleLink()),
133
                'text' => (!$slackMessage->getQuoteText() ? '' : $slackMessage->getQuoteText()),
134
                'color' => $this->quoteTypeColor($slackMessage->getQuoteType()),
135
                'mrkdwn_in' => ['text', 'pretext'],
136
            ];
137
        }
138
139
        return json_encode($return, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
140
    }
141
142
    /**
143
     * @param string $postBody
144
     * @return bool
145
     */
146
    private function sendRequest(string $postBody): bool
147
    {
148
        $request = $this->guzzleClient->post($this->config['api_url'], ['body' => $postBody]);
149
        if (!in_array($request->getStatusCode(), self::ALLOWED_RESPONSE_STATUSES)) {
150
            return false;
151
        }
152
153
        return true;
154
    }
155
}
156