Completed
Push — master ( 360ac5...2ab452 )
by Alexey
07:01 queued 03:11
created

SlackBot::getConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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
        $return = [];
109
110
        $this->validator->validateMessage($slackMessage);
111
        $slackMessage = $this->validator->setDefaultsForEmptyFields($slackMessage, $this->getConfig());
112
113
        $return['text'] = $slackMessage->getText();
114
        $return['mrkdwn'] = true;
115
116
        if ($slackMessage->isShowQuote()) {
117
            $return['attachments'] = [
118
                'fallback' => $slackMessage->getText(),
119
                'pretext' => $slackMessage->getText(),
120
                'fields' => [
121
                    'title' => (!$slackMessage->getQuoteTitle() ? '' : $slackMessage->getQuoteTitle()),
122
                    'title_link' => (!$slackMessage->getQuoteTitleLink() ? '' : $slackMessage->getQuoteTitleLink()),
123
                    'text' => (!$slackMessage->getQuoteText() ? '' : $slackMessage->getQuoteText()),
124
                    'color' => $this->quoteTypeColor($slackMessage->getQuoteType()),
125
                    'mrkdwn_in' => ['text', 'pretext']
126
                ]
127
            ];
128
        }
129
130
        return json_encode($return, JSON_UNESCAPED_UNICODE);
131
    }
132
133
    /**
134
     * @param string $postBody
135
     * @return bool
136
     */
137
    private function sendRequest(string $postBody): bool
138
    {
139
        $request = $this->guzzleClient->post($this->config['api_url'], ['body' => $postBody]);
140
        if (!in_array($request->getStatusCode(), [200, 301, 302])) {
141
            return false;
142
        }
143
144
        return true;
145
    }
146
}
147