Passed
Push — master ( 6c52eb...4d128c )
by Jacques
01:58
created

Client::setBearerToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
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-2018 Jacques Marneweck.  All rights strictly reserved.
10
 * @license   MIT
11
 */
12
13
namespace Jacques\Smartcall\HttpClient;
14
15
class Client extends \GuzzleHttp\Client
16
{
17
    /**
18
     * @const string Version number
19
     */
20
    const VERSION = '0.0.1';
21
22
    /**
23
     * Defaults to expecting that Apache Tomcat runs on port 8080 on localhost
24
     * (127.0.0.1).
25
     *
26
     * @var array[]
27
     */
28
    protected $options = [
29
        'scheme'   => 'https',
30
        'hostname' => 'localhost',
31
        'port'     => '8080',
32
        'token'    => null,
33
        'username' => null,
34
        'password' => null,
35
    ];
36
37
    /**
38
     * @param   $options array
39
     */
40 20
    public function __construct($options = [])
41
    {
42
        /*
43
         * Allow on instantiation to overwrite the defaults
44
         */
45 20
        $this->options = array_merge(
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge($this->options, $options) of type array is incompatible with the declared type array<integer,array> of property $options.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
46 20
            $this->options,
47 20
            $options
48
        );
49
        $config = [
50 20
            'base_uri' => sprintf(
51 20
                '%s://%s:%s/',
52 20
                $this->options['scheme'],
53 20
                $this->options['hostname'],
54 20
                $this->options['port']
55
            ),
56
            'verify'  => false,
57
            'headers' => [
58 20
                'User-Agent' => 'SmartcallRestfulAPIClient-PHP/'.self::VERSION.' '.\GuzzleHttp\default_user_agent(),
59
            ],
60
        ];
61 20
        parent::__construct($config);
62 20
    }
63
64
    /**
65
     * Set the bearer token.
66
     *
67
     * @param string $token Bearer Token from Auth request
68
     */
69 11
    public function setBearerToken($token)
70
    {
71 11
        $this->options['token'] = $token;
72 11
    }
73
74
    /**
75
     * Authenticate and get Bearer token from SmartCall.
76
     *
77
     * @param string $username
78
     * @param string $password
79
     *
80
     * @throws Exception
81
     *
82
     * @return array
83
     */
84 3
    public function auth($username, $password)
85
    {
86
        try {
87 3
            $response = $this->post(
88 3
                '/webservice/auth',
89
                [
90
                    'headers' => [
91 3
                        'Authorization' => sprintf(
92 3
                            'Basic %s',
93 3
                            base64_encode(
94 3
                                sprintf(
95 3
                                    '%s:%s',
96 3
                                    $username,
97 3
                                    $password
98
                                )
99
                            )
100
                        ),
101
                    ],
102
                ]
103
            );
104
105
            return [
106 1
                'status'    => 'ok',
107 1
                'http_code' => $response->getStatusCode(),
108 1
                'body'      => (string) $response->getBody(),
109
            ];
110 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
111 2
            return $this->clientError($e);
112
        } catch (\GuzzleHttp\Exception\ServerException $e) {
113
            return $this->parseError($e);
114
        }
115
    }
116
117
    /**
118
     * Authenticate and invalidates all the user allocated tokens.
119
     *
120
     * @throws Exception
121
     *
122
     * @return array
123
     */
124 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...
125
    {
126
        try {
127 2
            $response = $this->delete(
128 2
                '/webservice/auth',
129
                [
130
                    'headers' => [
131 2
                        'Authorization' => sprintf(
132 2
                            'Bearer %s',
133 2
                            $this->options['token']
134
                        ),
135
                    ],
136
                ]
137
            );
138
139
            return [
140 1
                'status'    => 'ok',
141 1
                'http_code' => $response->getStatusCode(),
142 1
                'body'      => (string) $response->getBody(),
143
            ];
144 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
145 1
            return $this->clientError($e);
146
        } catch (\GuzzleHttp\Exception\ServerException $e) {
147
            return $this->parseError($e);
148
        }
149
    }
150
151
    /**
152
     * Authenticate and invalidates all the user allocated tokens.
153
     *
154
     * @param string $username
155
     * @param string $password
156
     *
157
     * @throws Exception
158
     *
159
     * @return array
160
     */
161 3 View Code Duplication
    public function authFlush($username = null, $password = null)
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...
162
    {
163
        try {
164 3
            $response = $this->delete(
165 3
                '/webservice/auth/token',
166
                [
167
                    'headers' => [
168 3
                        'Authorization' => $this->bearerOrBasic($username, $password),
169
                    ],
170
                ]
171
            );
172
173
            return [
174 2
                'status'    => 'ok',
175 2
                'http_code' => $response->getStatusCode(),
176 2
                'body'      => (string) $response->getBody(),
177
            ];
178 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
179 1
            return $this->clientError($e);
180
        } catch (\GuzzleHttp\Exception\ServerException $e) {
181
            return $this->parseError($e);
182
        }
183
    }
184
185
    /**
186
     * Authenticate and gets the number of available session tokens.
187
     *
188
     * @param string $username
189
     * @param string $password
190
     *
191
     * @throws Exception
192
     *
193
     * @return array
194
     */
195 3 View Code Duplication
    public function authToken($username = null, $password = null)
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...
196
    {
197
        try {
198 3
            $response = $this->get(
199 3
                '/webservice/auth/token',
200
                [
201
                    'headers' => [
202 3
                        'Authorization' => $this->bearerOrBasic($username, $password),
203
                    ],
204
                ]
205
            );
206
207
            return [
208 1
                'status'    => 'ok',
209 1
                'http_code' => $response->getStatusCode(),
210 1
                'body'      => (string) $response->getBody(),
211
            ];
212 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
213 2
            return $this->clientError($e);
214
        } catch (\GuzzleHttp\Exception\ServerException $e) {
215
            return $this->parseError($e);
216
        }
217
    }
218
219
    /**
220
     * Authenticate and request period based cashup reports.
221
     *
222
     * @param string $dealerMsisdn
223
     * @param string $start
224
     * @param string $end
225
     *
226
     * @throws Exception
227
     *
228
     * @return array
229
     */
230
    public function cashup($dealerMsisdn, $start, $end)
231
    {
232
        try {
233
            $response = $this->post(
234
                '/webservice/smartload/cashup',
235
                [
236
                    'headers' => [
237
                        'Authorization' => sprintf(
238
                            'Bearer %s',
239
                            $this->options['token']
240
                        ),
241
                    ],
242
                    'json'    => [
243
                        'smartloadId' => $dealerMsisdn,
244
                        'startDate'   => $start,
245
                        'endDate'     => $end,
246
                    ],
247
                ]
248
            );
249
250
            return [
251
                'status'    => 'ok',
252
                'http_code' => $response->getStatusCode(),
253
                'body'      => (string) $response->getBody(),
254
            ];
255
        } catch (\GuzzleHttp\Exception\ClientException $e) {
256
            return $this->clientError($e);
257
        } catch (\GuzzleHttp\Exception\ServerException $e) {
258
            return $this->parseError($e);
259
        }
260
    }
261
262
    /**
263
     * Authenticate and request current day cashup report.
264
     *
265
     * @param string $dealerMsisdn
266
     *
267
     * @throws Exception
268
     *
269
     * @return array
270
     */
271 View Code Duplication
    public function cashupToday($dealerMsisdn)
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...
272
    {
273
        try {
274
            $response = $this->get(
275
                sprintf(
276
                    '/webservice/smartload/cashup/%s',
277
                    $dealerMsisdn
278
                ),
279
                [
280
                    'headers' => [
281
                        'Authorization' => sprintf(
282
                            'Bearer %s',
283
                            $this->options['token']
284
                        ),
285
                    ],
286
                ]
287
            );
288
289
            return [
290
                'status'    => 'ok',
291
                'http_code' => $response->getStatusCode(),
292
                'body'      => (string) $response->getBody(),
293
            ];
294
        } catch (\GuzzleHttp\Exception\ClientException $e) {
295
            return $this->clientError($e);
296
        } catch (\GuzzleHttp\Exception\ServerException $e) {
297
            return $this->parseError($e);
298
        }
299
    }
300
301
    /**
302
     * Authenticate and retrieves a list of all available networks.
303
     *
304
     * @throws Exception
305
     *
306
     * @return array
307
     */
308 2 View Code Duplication
    public function network($id)
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...
309
    {
310
        try {
311 2
            $response = $this->get(
312 2
                sprintf(
313 2
                    '/webservice/smartload/networks/%d',
314 2
                    $id
315
                ),
316
                [
317
                    'headers' => [
318 2
                        'Authorization' => sprintf(
319 2
                            'Bearer %s',
320 2
                            $this->options['token']
321
                        ),
322
                    ],
323
                ]
324
            );
325
326
            return [
327 1
                'status'    => 'ok',
328 1
                'http_code' => $response->getStatusCode(),
329 1
                'body'      => (string) $response->getBody(),
330
            ];
331 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
332 1
            return $this->clientError($e);
333
        } catch (\GuzzleHttp\Exception\ServerException $e) {
334
            return $this->parseError($e);
335
        }
336
    }
337
338
    /**
339
     * Authenticate and retrieves a list of all available networks.
340
     *
341
     * @throws Exception
342
     *
343
     * @return array
344
     */
345 2 View Code Duplication
    public function networks()
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...
346
    {
347
        try {
348 2
            $response = $this->get(
349 2
                '/webservice/smartload/networks',
350
                [
351
                    'headers' => [
352 2
                        'Authorization' => sprintf(
353 2
                            'Bearer %s',
354 2
                            $this->options['token']
355
                        ),
356
                    ],
357
                ]
358
            );
359
360
            return [
361 1
                'status'    => 'ok',
362 1
                'http_code' => $response->getStatusCode(),
363 1
                'body'      => (string) $response->getBody(),
364
            ];
365 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
366 1
            return $this->clientError($e);
367
        } catch (\GuzzleHttp\Exception\ServerException $e) {
368
            return $this->parseError($e);
369
        }
370
    }
371
372
    /**
373
     * Test SmartCall is responding.
374
     *
375
     * @throws Exception
376
     *
377
     * @return array
378
     */
379 1
    public function ping()
380
    {
381
        try {
382 1
            $response = $this->get(
383 1
                '/webservice/test/ping'
384
            );
385
386
            return [
387 1
                'status'    => 'ok',
388 1
                'http_code' => $response->getStatusCode(),
389 1
                'body'      => (string) $response->getBody(),
390
            ];
391
        } catch (\GuzzleHttp\Exception\ClientException $e) {
392
            return $this->clientError($e);
393
        } catch (\GuzzleHttp\Exception\ServerException $e) {
394
            return $this->parseError($e);
395
        }
396
    }
397
398
    /**
399
     * Authenticate and retrieves a list of all available networks.
400
     *
401
     * @throws Exception
402
     *
403
     * @return array
404
     */
405 2 View Code Duplication
    public function products($id)
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...
406
    {
407
        try {
408 2
            $response = $this->get(
409 2
                sprintf(
410 2
                    '/webservice/smartload/products/%d',
411 2
                    $id
412
                ),
413
                [
414
                    'headers' => [
415 2
                        'Authorization' => sprintf(
416 2
                            'Bearer %s',
417 2
                            $this->options['token']
418
                        ),
419
                    ],
420
                ]
421
            );
422
423
            return [
424 1
                'status'    => 'ok',
425 1
                'http_code' => $response->getStatusCode(),
426 1
                'body'      => (string) $response->getBody(),
427
            ];
428 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
429 1
            return $this->clientError($e);
430
        } catch (\GuzzleHttp\Exception\ServerException $e) {
431
            return $this->parseError($e);
432
        }
433
    }
434
435
    /**
436
     * Parse the java exception that we receive from Smartcall's Tomcat's.
437
     *
438
     * @param \GuzzleHttp\Exception\ServerException $exception
439
     *
440
     * @return array
441
     */
442 9 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...
443
    {
444 9
        $body = (string) $exception->getResponse()->getBody();
445
446
        return [
447 9
            'status'    => 'error',
448 9
            'http_code' => $exception->getResponse()->getStatusCode(),
449 9
            'body'      => json_decode($body),
450
        ];
451
    }
452
453
    /**
454
     * Parse the java exception that we receive from Smartcall's Tomcat's.
455
     *
456
     * @param \GuzzleHttp\Exception\ServerException $exception
457
     *
458
     * @return array
459
     */
460 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...
461
    {
462
        $body = (string) $exception->getResponse()->getBody();
463
        preg_match('!<p><b>type</b> Exception report</p><p><b>message</b> <u>(.*[^</u>])</u></p><p><b>description</b>!', $body, $matches);
464
        return [
465
            'status'    => 'error',
466
            'http_code' => $exception->getResponse()->getStatusCode(),
467
            'body'      => $matches['1'],
468
        ];
469
    }
470
471
    /**
472
     * Use basic authentication header content if bearer token  is not set.
473
     *
474
     * @param string $username
475
     * @param string $password
476
     *
477
     * @return string
478
     */
479 6
    private function bearerOrBasic($username = null, $password = null)
480
    {
481 6
        if (is_null($username)) {
482 2
            return sprintf(
483 2
                'Bearer %s',
484 2
                $this->options['token']
485
            );
486
        }
487
488 4
        return sprintf(
489 4
            'Basic %s',
490 4
            base64_encode(
491 4
                sprintf(
492 4
                    '%s:%s',
493 4
                    $username,
494 4
                    $password
495
                )
496
            )
497
        );
498
    }
499
}
500