Passed
Push — master ( fd7b57...b473d1 )
by Simon
02:17
created

SlackStatusController::getRestfulService()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
4
/**
5
 * Class SlackStatusController
6
 *
7
 */
8
class SlackStatusController extends Controller
0 ignored issues
show
Bug introduced by
The type Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
{
10
    private static $allowed_actions = [
11
        'usercount',
12
        'badge'
13
    ];
14
15
    /**
16
     * @return int
17
     * @throws ValidationException
18
     */
19
    public function usercount()
20
    {
21
        /** @var SiteConfig $config */
22
        $config = SiteConfig::current_site_config();
0 ignored issues
show
Bug introduced by
The type SiteConfig was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
        // Break if there is a configuration error
24
        if (!$config->SlackURL || !$config->SlackToken || !$config->SlackChannel) {
25
            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...
26
        }
27
        $params = $this->getRequestParams($config);
28
29
        return $this->getStatus($config, $params);
30
    }
31
32
    /**
33
     * @return SS_HTTPResponse
34
     * @throws ValidationException
35
     */
36
    public function badge()
37
    {
38
        $config = SiteConfig::current_site_config();
39
        $params = $this->getRequestParams($config);
40
        $count = $this->getStatus($config, $params);
41
        list($width, $pos) = $this->getSVGSettings($count);
42
43
        $body = $this->renderWith('SVGTemplate', ['Count' => $count, 'Width' => $width, 'Pos' => $pos]);
44
        $response = new SS_HTTPResponse($body);
0 ignored issues
show
Bug introduced by
The type SS_HTTPResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
45
        $response->addHeader('Content-Type', 'image/svg+xml');
46
47
        return $response;
48
    }
49
50
51
    protected function getRequestParams($config)
52
    {
53
        return [
54
            'token'   => $config->SlackToken,
55
            'type'    => 'post',
56
            'channel' => $config->SlackChannel,
57
            'scope'   => 'identify,read,post,client',
58
        ];
59
    }
60
61
    /**
62
     * @param SiteConfig $config
63
     * @param array $params
64
     * @return int
65
     * @throws ValidationException
66
     */
67
    public function getStatus($config, $params = [])
68
    {
69
        /** @var SlackUserCount $count */
70
        $count = SlackUserCount::get()->first();
71
        // To limit the amount of API requests, only update the count
72
        // once every 3 hours
73
        if ($count) {
74
            $dateTime = SS_Datetime::create();
0 ignored issues
show
Bug introduced by
The type SS_Datetime was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
75
            $dateTime->setValue($count->LastEdited);
76
            $diff = explode(' ', $dateTime->TimeDiffIn('hours'));
77
            if ($diff[0] < 3) {
78
                return $count->UserCount;
79
            }
80
        } else {
81
            $count = SlackUserCount::create();
82
        }
83
84
        return $this->getSlackCount($config, $params, $count);
85
    }
86
87
    /**
88
     * @param SiteConfig $config
89
     * @param array $params
90
     * @param SlackUserCount $count
91
     * @return int
92
     * @throws \ValidationException
93
     */
94
    protected function getSlackCount($config, $params, $count)
95
    {
96
        list($url, $service) = $this->getRestfulService($config);
97
98
        $response = $service->request($url, 'POST', $params);
99
        $result = Convert::json2array($response->getBody());
0 ignored issues
show
Bug introduced by
The type Convert was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
100
101
        return $this->validateResponse($count, $result);
102
    }
103
104
    /**
105
     * @param $count
106
     * @return array
107
     */
108
    public function getSVGSettings($count)
109
    {
110
        if ($count < 100) {
111
            $width = 25;
112
            $pos = 60;
113
        } elseif ($count < 1000) {
114
            $width = 35;
115
            $pos = 65;
116
        } else {
117
            $width = 45;
118
            $pos = 70;
119
        }
120
121
        return [$width, $pos];
122
    }
123
124
    /**
125
     * @param $config
126
     * @return array
127
     */
128
    public function getRestfulService($config)
129
    {
130
        $now = time();
131
        $baseURL = $config->SlackURL;
132
        $baseURL = (substr($baseURL, -1) === '/') ? $baseURL : $baseURL . '/';
133
        $url = 'api/channels.info?t=' . $now;
134
135
        /** @var RestfulService $service with an _uncached_ response */
136
        $service = RestfulService::create($baseURL, 0);
0 ignored issues
show
Bug introduced by
The type RestfulService was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
137
138
        return array($url, $service);
139
    }
140
141
    /**
142
     * @param SlackUserCount $count
143
     * @param array $result
144
     * @return int
145
     */
146
    public function validateResponse($count, $result)
147
    {
148
        if (isset($result['ok']) && $result['ok']) {
149
            $userCount = count($result['channel']['members']);
150
            $count->UserCount = $userCount;
151
            $count->write();
152
153
            return $userCount;
154
        }
155
156
        return 0;
157
    }
158
}
159