GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — 2.0 ( 90d528...00d2e6 )
by Nico
03:49
created

Base::getApiKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
namespace Datatrics\API\Modules;
3
4
class Base
5
{
6
    const CLIENT_VERSION = '2.0.0';
7
8
    const HTTP_GET = 'GET';
9
    const HTTP_POST = 'POST';
10
    const HTTP_PUT = 'PUT';
11
    const HTTP_DELETE = 'DELETE';
12
13
    /**
14
     * @var string
15
     */
16
    protected $api_endpoint = 'https://api.datatrics.com/2.0';
17
18
    /**
19
     * @var string
20
     */
21
    protected $api_key;
22
23
    /**
24
     * Base constructor.
25
     * @param $apikey
26
     * @param $endpoint
27
     */
28 13
    public function __construct($apikey, $endpoint)
29
    {
30 13
        $this->api_key = $apikey;
31 13
        $this->api_endpoint .= $endpoint;
32 13
    }
33
34
    /**
35
     * @return string
36
     */
37
    protected function getApiEndpoint()
38
    {
39
        return $this->api_endpoint;
40
    }
41
42
    /**
43
     * @param string $api_endpoint
44
     * @return Base
45
     */
46
    protected function setApiEndpoint($api_endpoint)
47
    {
48
        $this->api_endpoint = $api_endpoint;
49
        return $this;
50
    }
51
52
    /**
53
     * @return string
54
     */
55
    protected function getApiKey()
56
    {
57
        return $this->api_key;
58
    }
59
60
    /**
61
     * @param string $api_key
62
     * @return Base
63
     */
64
    protected function setApiKey($api_key)
65
    {
66
        $this->api_key = $api_key;
67
        return $this;
68
    }
69
70
    /**
71
     * @throws \Exception
72
     */
73 9
    public function checkApiKey()
74
    {
75 9
        if (empty($this->api_key)) {
76 2
            throw new \Exception('You have not set an api key. Please use setApiKey() to set the API key.');
77
        }
78 7
    }
79
80
    /**
81
     * @param $url
82
     * @param null|array $payload
83
     * @return string
84
     */
85 6
    public function getUrl($url, $payload = null)
86
    {
87 6
        $url = $this->api_endpoint.$url;
88 6
        if ($payload) {
89
            $url .= "?".http_build_query($payload);
90
        }
91 6
        return $url;
92
    }
93
94
    /**
95
     * @param int   $responseCode
96
     * @param array $responseBody
97
     *
98
     * @throws \Exception
99
     */
100 6
    private function handleResponseError($responseCode, $responseBody)
101
    {
102 6
        $errorMessage = 'Unknown error: ' . $responseCode;
103
104 6
        if ($responseBody && array_key_exists('error', $responseBody)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $responseBody of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
105 2
            $errorMessage = $responseBody['error']['message'];
106
        }
107 6
        if ($responseBody && array_key_exists('message', $responseBody)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $responseBody of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
108 4
            $errorMessage = $responseBody['message'];
109
        }
110
111
112 6
        throw new \Exception($errorMessage, $responseCode);
113
    }
114
115
    /**
116
     * @param resource $curlHandle
117
     *
118
     * @throws \Exception
119
     */
120
    private function handleCurlError($curlHandle)
121
    {
122
        $errorMessage = 'Curl error: ' . curl_error($curlHandle);
123
124
        throw new \Exception($errorMessage, curl_errno($curlHandle));
125
    }
126
127
    /**
128
     * Perform an http call. This method is used by the resource specific classes.
129
     *
130
     * @param $method
131
     * @param $url
132
     * @param $payload
133
     *
134
     * @return string|object
135
     *
136
     * @throws \Exception
137
     */
138 7
    public function request($method, $url, $payload = null)
139
    {
140 7
        $this->checkApiKey();
141
142 6
        $user_agent = 'Datatrics php-api '.self::CLIENT_VERSION;
143
        $request_headers = array(
144 6
            'Accept: application/json',
145 6
            'X-apikey: '.$this->api_key,
146 6
            'X-client-name: '.$user_agent,
147 6
            'X-datatrics-client-info: '.php_uname(),
148
        );
149
150 6
        if ($method == 'post' || $method == 'put') {
151
            if (!$payload || !is_array($payload)) {
152
                throw new \Exception('Invalid payload', 100);
153
            }
154
            $request_headers['Content-Type'] = 'application/json';
155
            $curlOptions = array(
156
                CURLOPT_URL           => $this->getUrl($url),
157
                CURLOPT_CUSTOMREQUEST => strtoupper($method),
158
                CURLOPT_POSTFIELDS    => json_encode($payload),
159
            );
160 6
        } elseif ($method == 'delete') {
161
            $curlOptions = array(
162
                CURLOPT_URL           => $this->getUrl($url),
163
                CURLOPT_CUSTOMREQUEST => 'DELETE',
164
            );
165
        } else {
166
            $curlOptions = array(
167 6
                CURLOPT_URL => $this->getUrl($url, $payload),
168
            );
169
        }
170
171
        $curlOptions += array(
172 6
            CURLOPT_HEADER         => false,
173 6
            CURLOPT_RETURNTRANSFER => true,
174 6
            CURLOPT_SSL_VERIFYPEER => false,
175 6
            CURLOPT_USERAGENT      => $user_agent,
176 6
            CURLOPT_SSLVERSION     => 6,
177 6
            CURLOPT_HTTPHEADER     => $request_headers
178
        );
179
180 6
        $curlHandle = curl_init();
181
182 6
        curl_setopt_array($curlHandle, $curlOptions);
183
184 6
        $responseBody = curl_exec($curlHandle);
185
186 6
        if (curl_errno($curlHandle)) {
187
            $this->handleCurlError($curlHandle);
188
        }
189
190 6
        $responseBody = json_decode($responseBody, true);
191 6
        $responseCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
192
193 6
        curl_close($curlHandle);
194
195
196 6
        if ($responseCode < 200 || $responseCode > 299 || ($responseBody && array_key_exists('error', $responseBody))) {
197 6
            $this->handleResponseError($responseCode, $responseBody);
198
        }
199
        if ($responseCode < 200 || $responseCode > 299 || ($responseBody && array_key_exists('message', $responseBody))) {
200
            $this->handleResponseError($responseCode, $responseBody);
201
        }
202
203
        return $responseBody;
204
    }
205
}
206