Passed
Pull Request — master (#11)
by Simon
01:41
created

SlackStatusController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 147
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 147
rs 10
c 0
b 0
f 0
wmc 18

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getRequestParams() 0 8 1
A getClient() 0 6 2
A usercount() 0 11 4
A validateResponse() 0 11 3
A getStatus() 0 18 3
A getSVGSettings() 0 14 3
A getSlackCount() 0 9 1
A badge() 0 12 1
1
<?php
2
3
namespace Firesphere\StripeSlack\Controller;
4
5
use Firesphere\StripeSlack\Model\SlackUserCount;
6
use GuzzleHttp\Client;
7
use SilverStripe\Control\Controller;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Core\Convert;
10
use SilverStripe\ORM\FieldType\DBDatetime;
11
use SilverStripe\ORM\ValidationException;
12
use SilverStripe\SiteConfig\SiteConfig;
13
14
/**
15
 * Class SlackStatusController
16
 *
17
 */
18
class SlackStatusController extends Controller
19
{
20
    private static $allowed_actions = [
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
21
        'usercount',
22
        'badge'
23
    ];
24
25
    /**
26
     * @return int
27
     * @throws ValidationException
28
     */
29
    public function usercount()
30
    {
31
        /** @var SiteConfig $config */
32
        $config = SiteConfig::current_site_config();
33
        // Break if there is a configuration error
34
        if (!$config->SlackURL || !$config->SlackToken || !$config->SlackChannel) {
35
            return '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return '' returns the type string which is incompatible with the documented return type integer.
Loading history...
36
        }
37
        $params = $this->getRequestParams($config);
38
39
        return $this->getStatus($config, $params);
40
    }
41
42
    /**
43
     * @return HTTPResponse
44
     * @throws ValidationException
45
     */
46
    public function badge()
47
    {
48
        $config = SiteConfig::current_site_config();
49
        $params = $this->getRequestParams($config);
50
        $count = $this->getStatus($config, $params);
51
        list($width, $pos) = $this->getSVGSettings($count);
52
53
        $body = $this->renderWith('SVGTemplate', ['Count' => $count, 'Width' => $width, 'Pos' => $pos]);
54
        $response = new HTTPResponse($body);
55
        $response->addHeader('Content-Type', 'image/svg+xml');
56
57
        return $response;
58
    }
59
60
61
    protected function getRequestParams($config)
62
    {
63
        return [
64
            'form_params' => [
65
                'token'   => $config->SlackToken,
66
                'type'    => 'post',
67
                'channel' => $config->SlackChannel,
68
                'scope'   => 'identify,read,post,client',
69
            ]
70
        ];
71
    }
72
73
    /**
74
     * @param SiteConfig $config
75
     * @param array $params
76
     * @return int
77
     * @throws ValidationException
78
     */
79
    public function getStatus($config, $params = [])
80
    {
81
        /** @var SlackUserCount $count */
82
        $count = SlackUserCount::get()->first();
83
        // To limit the amount of API requests, only update the count
84
        // once every 3 hours
85
        if ($count) {
86
            $dateTime = DBDatetime::create();
87
            $dateTime->setValue($count->LastEdited);
88
            $diff = explode(' ', $dateTime->TimeDiffIn('hours'));
89
            if ($diff[0] < 3) {
90
                return $count->UserCount;
91
            }
92
        } else {
93
            $count = SlackUserCount::create();
94
        }
95
96
        return $this->getSlackCount($config, $params, $count);
97
    }
98
99
    /**
100
     * @param SiteConfig $config
101
     * @param array $params
102
     * @param SlackUserCount $count
103
     * @return int
104
     * @throws ValidationException
105
     */
106
    protected function getSlackCount($config, $params, $count)
107
    {
108
        $service = $this->getClient($config);
109
        $url = 'api/channels.info?t=' . time();
110
111
        $response = $service->request('POST', $url, $params);
112
        $result = Convert::json2array($response->getBody());
113
114
        return $this->validateResponse($count, $result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of Firesphere\StripeSlack\C...ler::validateResponse() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

114
        return $this->validateResponse($count, /** @scrutinizer ignore-type */ $result);
Loading history...
115
    }
116
117
    /**
118
     * @param $count
119
     * @return array
120
     */
121
    public function getSVGSettings($count)
122
    {
123
        if ($count < 100) {
124
            $width = 25;
125
            $pos = 60;
126
        } elseif ($count < 1000) {
127
            $width = 35;
128
            $pos = 65;
129
        } else {
130
            $width = 45;
131
            $pos = 70;
132
        }
133
134
        return [$width, $pos];
135
    }
136
137
    /**
138
     * @param $config
139
     * @return Client
140
     */
141
    public function getClient($config)
142
    {
143
        $baseURL = $config->SlackURL;
144
        $baseURL = (substr($baseURL, -1) === '/') ? $baseURL : $baseURL . '/';
145
146
        return new Client(['base_uri' => $baseURL]);
147
    }
148
149
    /**
150
     * @param SlackUserCount $count
151
     * @param array $result
152
     * @return int
153
     */
154
    public function validateResponse($count, $result)
155
    {
156
        if (isset($result['ok']) && $result['ok']) {
157
            $userCount = count($result['channel']['members']);
158
            $count->UserCount = $userCount;
159
            $count->write();
160
161
            return $userCount;
162
        }
163
164
        return 0;
165
    }
166
}
167