Passed
Push — master ( d53117...da6533 )
by Jacques
10:23
created

Client::authDelete()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 23

Duplication

Lines 23
Ratio 100 %

Code Coverage

Tests 9
CRAP Score 3.054

Importance

Changes 0
Metric Value
dl 23
loc 23
ccs 9
cts 11
cp 0.8182
rs 9.552
c 0
b 0
f 0
cc 3
nc 5
nop 0
crap 3.054
1
<?php declare(strict_types=1);
2
/**
3
 * SmartCall Restful API (v3) HTTP Client.
4
 *
5
 * PLEASE NOTE: The interface is very fluid while the intial integration
6
 * is taking place.  It will be refactored in the near future.
7
 *
8
 * @author    Jacques Marneweck <[email protected]>
9
 * @copyright 2017-2019 Jacques Marneweck.  All rights strictly reserved.
10
 * @license   MIT
11
 */
12
13
namespace Jacques\Smartcall\HttpClient;
14
15
use Jacques\Smartcall\HttpClient\Traits\SmartLoad;
16
use Jacques\Smartcall\HttpClient\Traits\SmartRica;
17
18
class Client extends \GuzzleHttp\Client
19
{
20
    use SmartLoad;
21
    use SmartRica;
22
23
    /**
24
     * @const string Version number
25
     */
26
    const VERSION = '0.0.1';
27
28
    /**
29
     * Defaults to expecting that Apache Tomcat runs on port 8080 on localhost
30
     * (127.0.0.1).
31
     *
32
     * @var array
33
     */
34
    protected $options = [
35
        'scheme'   => 'https',
36
        'hostname' => 'localhost',
37
        'port'     => '8080',
38
        'token'    => null,
39
        'username' => null,
40
        'password' => null,
41
    ];
42
43
    /**
44
     * @param array $options
45
     */
46 57
    public function __construct($options = [])
47
    {
48
        /*
49
         * Allow on instantiation to overwrite the defaults
50
         */
51 57
        $this->options = array_merge(
52 57
            $this->options,
53 57
            $options
54
        );
55
        $config = [
56 57
            'base_uri' => sprintf(
57 57
                '%s://%s:%s/',
58 57
                $this->options['scheme'],
59 57
                $this->options['hostname'],
60 57
                $this->options['port']
61
            ),
62
            'verify'  => false,
63
            'headers' => [
64 57
                'User-Agent' => 'SmartcallRestfulAPIClient-PHP/'.self::VERSION.' '.\GuzzleHttp\default_user_agent(),
65
            ],
66
        ];
67 57
        parent::__construct($config);
68 57
    }
69
70
    /**
71
     * Set the bearer token.
72
     *
73
     * @param string $token Bearer Token from Auth request
74
     */
75 43
    public function setBearerToken($token)
76
    {
77 43
        $this->options['token'] = $token;
78 43
    }
79
80
    /**
81
     * Set the password for basic authentication.
82
     *
83
     * @param string $password Password for use with basic authentication
84
     */
85 1
    public function setPassword($password)
86
    {
87 1
        $this->options['password'] = $password;
88 1
    }
89
90
    /**
91
     * Set the username for basic authentication.
92
     *
93
     * @param string $username Username for use with basic authentication
94
     */
95 1
    public function setUsername($username)
96
    {
97 1
        $this->options['username'] = $username;
98 1
    }
99
100
    /**
101
     * Authenticate and get Bearer token from SmartCall.
102
     *
103
     * @throws Exception
104
     *
105
     * @return array
106
     */
107 3 View Code Duplication
    public function auth()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
    {
109
        try {
110 3
            $response = $this->post(
111 3
                '/webservice/auth',
112
                [
113
                    'headers' => [
114 3
                        'Authorization' => $this->bearerOrBasic(),
115
                    ],
116
                ]
117
            );
118
119
            return [
120 1
                'status'    => 'ok',
121 1
                'http_code' => $response->getStatusCode(),
122 1
                'body'      => (string) $response->getBody(),
123
            ];
124 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
125 2
            return $this->clientError($e);
126
        } catch (\GuzzleHttp\Exception\ServerException $e) {
127
            return $this->parseError($e);
128
        }
129
    }
130
131
    /**
132
     * Authenticate and invalidates all the user allocated tokens.
133
     *
134
     * @throws Exception
135
     *
136
     * @return array
137
     */
138 2 View Code Duplication
    public function authDelete()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
139
    {
140
        try {
141 2
            $response = $this->delete(
142 2
                '/webservice/auth',
143
                [
144
                    'headers' => [
145 2
                        'Authorization' => $this->bearerOrBasic(),
146
                    ],
147
                ]
148
            );
149
150
            return [
151 1
                'status'    => 'ok',
152 1
                'http_code' => $response->getStatusCode(),
153 1
                'body'      => (string) $response->getBody(),
154
            ];
155 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
156 1
            return $this->clientError($e);
157
        } catch (\GuzzleHttp\Exception\ServerException $e) {
158
            return $this->parseError($e);
159
        }
160
    }
161
162
    /**
163
     * Authenticate and invalidates all the user allocated tokens.
164
     *
165
     * @throws Exception
166
     *
167
     * @return array
168
     */
169 3 View Code Duplication
    public function authFlush()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
    {
171
        try {
172 3
            $response = $this->delete(
173 3
                '/webservice/auth/token',
174
                [
175
                    'headers' => [
176 3
                        'Authorization' => $this->bearerOrBasic(),
177
                    ],
178
                ]
179
            );
180
181
            return [
182 2
                'status'    => 'ok',
183 2
                'http_code' => $response->getStatusCode(),
184 2
                'body'      => (string) $response->getBody(),
185
            ];
186 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
187 1
            return $this->clientError($e);
188
        } catch (\GuzzleHttp\Exception\ServerException $e) {
189
            return $this->parseError($e);
190
        }
191
    }
192
193
    /**
194
     * Authenticate and gets the number of available session tokens.
195
     *
196
     * @throws Exception
197
     *
198
     * @return array
199
     */
200 3 View Code Duplication
    public function authToken()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201
    {
202
        try {
203 3
            $response = $this->get(
204 3
                '/webservice/auth/token',
205
                [
206
                    'headers' => [
207 3
                        'Authorization' => $this->bearerOrBasic(),
208
                    ],
209
                ]
210
            );
211
212
            return [
213 1
                'status'    => 'ok',
214 1
                'http_code' => $response->getStatusCode(),
215 1
                'body'      => (string) $response->getBody(),
216
            ];
217 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
218 2
            return $this->clientError($e);
219
        } catch (\GuzzleHttp\Exception\ServerException $e) {
220
            return $this->parseError($e);
221
        }
222
    }
223
224
    /**
225
     * Gets the mobile network on which the SIM is connected.
226
     *
227
     * @param string $msisdn
228
     *
229
     * @throws Exception
230
     *
231
     * @return array
232
     */
233 4 View Code Duplication
    public function simnetwork($msisdn)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
234
    {
235
        try {
236 4
            $response = $this->get(
237 4
                sprintf(
238 4
                    '/webservice/utilities/simnetwork/%d',
239 4
                    $msisdn
240
                ),
241
                [
242
                    'headers' => [
243 4
                        'Authorization' => $this->bearerOrBasic(),
244
                    ],
245
                ]
246
            );
247
248
            return [
249 2
                'status'    => 'ok',
250 2
                'http_code' => $response->getStatusCode(),
251 2
                'body'      => (string) $response->getBody(),
252
            ];
253 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
254 2
            return $this->clientError($e);
255
        } catch (\GuzzleHttp\Exception\ServerException $e) {
256
            return $this->parseError($e);
257
        }
258
    }
259
260
    /**
261
     * Test SmartCall is responding.
262
     *
263
     * @throws Exception
264
     *
265
     * @return array
266
     */
267 1
    public function ping()
268
    {
269
        try {
270 1
            $response = $this->get(
271 1
                '/webservice/test/ping'
272
            );
273
274
            return [
275 1
                'status'    => 'ok',
276 1
                'http_code' => $response->getStatusCode(),
277 1
                'body'      => (string) $response->getBody(),
278
            ];
279
        } catch (\GuzzleHttp\Exception\ClientException $e) {
280
            return $this->clientError($e);
281
        } catch (\GuzzleHttp\Exception\ServerException $e) {
282
            return $this->parseError($e);
283
        }
284
    }
285
286
    /**
287
     * Parse the java exception that we receive from Smartcall's Tomcat's.
288
     *
289
     * @param \GuzzleHttp\Exception\ClientException $exception
290
     *
291
     * @return array
292
     */
293 26 View Code Duplication
    private function clientError(\GuzzleHttp\Exception\ClientException $exception)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
294
    {
295 26
        $body = (string) $exception->getResponse()->getBody();
296
297
        return [
298 26
            'status'    => 'error',
299 26
            'http_code' => $exception->getResponse()->getStatusCode(),
300 26
            'body'      => json_decode($body),
301
        ];
302
    }
303
304
    /**
305
     * Parse the java exception that we receive from Smartcall's Tomcat's.
306
     *
307
     * @param \GuzzleHttp\Exception\ServerException $exception
308
     *
309
     * @return array
310
     */
311 View Code Duplication
    private function parseError(\GuzzleHttp\Exception\ServerException $exception)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
312
    {
313
        $body = (string) $exception->getResponse()->getBody();
314
        preg_match('/<p><b>(JBWEB\d{6}): type<\/b> (JBWEB\d{6}): Exception report<\/p><p><b>(JBWEB\d{6}): message<\/b> <u>(.*[^<\/u>])<\/u><\/p><p><b>(JBWEB\d{6}): description<\/b> <u>(.+[^<\/u>])<\/u><\/p>/ims', $body, $matches);
315
316
        return [
317
            'status'    => 'error',
318
            'http_code' => $exception->getResponse()->getStatusCode(),
319
            'body'      => $matches['6'],
320
        ];
321
    }
322
323
    /**
324
     * Use basic authentication header content if bearer token  is not set.
325
     *
326
     * @return string
327
     */
328 52
    private function bearerOrBasic()
329
    {
330
        /**
331
         * Get the function calling this method.
332
         */
333 52
        $caller = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2)[1]['function'];
334
335
        if (
336 52
            !in_array(
337 52
                $caller,
338
                [
339 52
                    'auth',
340
                ]
341
            )
342
        ) {
343 49
            return sprintf(
344 49
                'Bearer %s',
345 49
                $this->options['token']
346
            );
347
        }
348
349 3
        return sprintf(
350 3
            'Basic %s',
351 3
            base64_encode(
352 3
                sprintf(
353 3
                    '%s:%s',
354 3
                    $this->options['username'],
355 3
                    $this->options['password']
356
                )
357
            )
358
        );
359
    }
360
}
361