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

SlackStatusController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 146
Duplicated Lines 0 %

Importance

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

8 Methods

Rating   Name   Duplication   Size   Complexity  
A usercount() 0 11 4
A getRequestParams() 0 8 1
A getClient() 0 6 2
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
    protected function getRequestParams($config)
43
    {
44
        return [
45
            'form_params' => [
46
                'token'   => $config->SlackToken,
47
                'type'    => 'post',
48
                'channel' => $config->SlackChannel,
49
                'scope'   => 'identify,read,post,client',
50
            ]
51
        ];
52
    }
53
54
    /**
55
     * @param SiteConfig $config
56
     * @param array $params
57
     * @return int
58
     * @throws ValidationException
59
     */
60
    public function getStatus($config, $params = [])
61
    {
62
        /** @var SlackUserCount $count */
63
        $count = SlackUserCount::get()->first();
64
        // To limit the amount of API requests, only update the count
65
        // once every 3 hours
66
        if ($count) {
67
            $dateTime = DBDatetime::create();
68
            $dateTime->setValue($count->LastEdited);
69
            $diff = explode(' ', $dateTime->TimeDiffIn('hours'));
70
            if ($diff[0] < 3) {
71
                return $count->UserCount;
72
            }
73
        } else {
74
            $count = SlackUserCount::create();
75
        }
76
77
        return $this->getSlackCount($config, $params, $count);
78
    }
79
80
    /**
81
     * @param SiteConfig $config
82
     * @param array $params
83
     * @param SlackUserCount $count
84
     * @return int
85
     * @throws ValidationException
86
     */
87
    protected function getSlackCount($config, $params, $count)
88
    {
89
        $service = $this->getClient($config);
90
        $url = 'api/channels.info?t=' . time();
91
92
        $response = $service->request('POST', $url, $params);
93
        $result = Convert::json2array($response->getBody());
94
95
        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

95
        return $this->validateResponse($count, /** @scrutinizer ignore-type */ $result);
Loading history...
96
    }
97
98
    /**
99
     * @param $config
100
     * @return Client
101
     */
102
    public function getClient($config)
103
    {
104
        $baseURL = $config->SlackURL;
105
        $baseURL = (substr($baseURL, -1) === '/') ? $baseURL : $baseURL . '/';
106
107
        return new Client(['base_uri' => $baseURL]);
108
    }
109
110
    /**
111
     * @param SlackUserCount $count
112
     * @param array $result
113
     * @return int
114
     */
115
    public function validateResponse($count, $result)
116
    {
117
        if (isset($result['ok']) && $result['ok']) {
118
            $userCount = count($result['channel']['members']);
119
            $count->UserCount = $userCount;
120
            $count->write();
121
122
            return $userCount;
123
        }
124
125
        return 0;
126
    }
127
128
    /**
129
     * @return HTTPResponse
130
     * @throws ValidationException
131
     */
132
    public function badge()
133
    {
134
        $config = SiteConfig::current_site_config();
135
        $params = $this->getRequestParams($config);
136
        $count = $this->getStatus($config, $params);
137
        list($width, $pos) = $this->getSVGSettings($count);
138
139
        $body = $this->renderWith('SVGTemplate', ['Count' => $count, 'Width' => $width, 'Pos' => $pos]);
140
        $response = new HTTPResponse($body);
141
        $response->addHeader('Content-Type', 'image/svg+xml');
142
143
        return $response;
144
    }
145
146
    /**
147
     * @param $count
148
     * @return array
149
     */
150
    public function getSVGSettings($count)
151
    {
152
        if ($count < 100) {
153
            $width = 25;
154
            $pos = 60;
155
        } elseif ($count < 1000) {
156
            $width = 35;
157
            $pos = 65;
158
        } else {
159
            $width = 45;
160
            $pos = 70;
161
        }
162
163
        return [$width, $pos];
164
    }
165
}
166