Passed
Push — master ( 360d7a...c06290 )
by Jacques
01:56
created

Client::network()   B

Complexity

Conditions 3
Paths 5

Size

Total Lines 29
Code Lines 18

Duplication

Lines 29
Ratio 100 %

Code Coverage

Tests 13
CRAP Score 3.0213

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 29
loc 29
ccs 13
cts 15
cp 0.8667
rs 8.8571
cc 3
eloc 18
nc 5
nop 1
crap 3.0213
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 17
    public function __construct($options = [])
41
    {
42
        /*
43
         * Allow on instantiation to overwrite the defaults
44
         */
45 17
        $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 17
            $this->options,
47 17
            $options
48
        );
49
        $config = [
50 17
            'base_uri' => sprintf(
51 17
                '%s://%s:%s/',
52 17
                $this->options['scheme'],
53 17
                $this->options['hostname'],
54 17
                $this->options['port']
55
            ),
56
            'verify'  => false,
57
            'headers' => [
58 17
                'User-Agent' => 'SmartcallRestfulAPIClient-PHP/'.self::VERSION.' '.\GuzzleHttp\default_user_agent(),
59
            ],
60
        ];
61 17
        parent::__construct($config);
62 17
    }
63
64
    /**
65
     * Set the bearer token.
66
     *
67
     * @param string $token Bearer Token from Auth request
68
     */
69 9
    public function setBearerToken($token)
70
    {
71 9
        $this->options['token'] = $token;
72 9
    }
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 View Code Duplication
    public function auth($username, $password)
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...
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 View Code Duplication
    public function authFlush($username, $password)
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
            $response = $this->delete(
165
                '/webservice/auth/token',
166
                [
167
                    'headers' => [
168
                        'Authorization' => sprintf(
169
                            'Basic %s',
170
                            base64_encode(
171
                                sprintf(
172
                                    '%s:%s',
173
                                    $username,
174
                                    $password
175
                                )
176
                            )
177
                        ),
178
                    ],
179
                ]
180
            );
181
182
            return [
183
                'status'    => 'ok',
184
                'http_code' => $response->getStatusCode(),
185
                'body'      => (string) $response->getBody(),
186
            ];
187
        } catch (\GuzzleHttp\Exception\ClientException $e) {
188
            return $this->clientError($e);
189
        } catch (\GuzzleHttp\Exception\ServerException $e) {
190
            return $this->parseError($e);
191
        }
192
    }
193
194
    /**
195
     * Authenticate and gets the number of available session tokens.
196
     *
197
     * @param string $username
198
     * @param string $password
199
     *
200
     * @throws Exception
201
     *
202
     * @return array
203
     */
204 3 View Code Duplication
    public function authToken($username, $password)
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...
205
    {
206
        try {
207 3
            $response = $this->get(
208 3
                '/webservice/auth/token',
209
                [
210
                    'headers' => [
211 3
                        'Authorization' => sprintf(
212 3
                            'Basic %s',
213 3
                            base64_encode(
214 3
                                sprintf(
215 3
                                    '%s:%s',
216 3
                                    $username,
217 3
                                    $password
218
                                )
219
                            )
220
                        ),
221
                    ],
222
                ]
223
            );
224
225
            return [
226 1
                'status'    => 'ok',
227 1
                'http_code' => $response->getStatusCode(),
228 1
                'body'      => (string) $response->getBody(),
229
            ];
230 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
231 2
            return $this->clientError($e);
232
        } catch (\GuzzleHttp\Exception\ServerException $e) {
233
            return $this->parseError($e);
234
        }
235
    }
236
237
    /**
238
     * Authenticate and request period based cashup reports.
239
     *
240
     * @param string $dealerMsisdn
241
     * @param string $start
242
     * @param string $end
243
     *
244
     * @throws Exception
245
     *
246
     * @return array
247
     */
248 View Code Duplication
    public function cashup($dealerMsisdn, $start, $end)
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...
249
    {
250
        try {
251
            $response = $this->post(
252
                '/webservice/smartload/cashup',
253
                [
254
                    'headers' => [
255
                        'Authorization' => sprintf(
256
                            'Bearer %s',
257
                            $this->options['token']
258
                        ),
259
                    ],
260
                    'json'    => [
261
                        'smartloadId' => $dealerMsisdn,
262
                        'startDate'   => $start,
263
                        'endDate'     => $end,
264
                    ],
265
                ]
266
            );
267
268
            return [
269
                'status'    => 'ok',
270
                'http_code' => $response->getStatusCode(),
271
                'body'      => (string) $response->getBody(),
272
            ];
273
        } catch (\GuzzleHttp\Exception\ClientException $e) {
274
            return $this->clientError($e);
275
        } catch (\GuzzleHttp\Exception\ServerException $e) {
276
            return $this->parseError($e);
277
        }
278
    }
279
280
    /**
281
     * Authenticate and request current day cashup report.
282
     *
283
     * @param string $dealerMsisdn
284
     *
285
     * @throws Exception
286
     *
287
     * @return array
288
     */
289 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...
290
    {
291
        try {
292
            $response = $this->get(
293
                sprintf(
294
                    '/webservice/smartload/cashup/%s',
295
                    $dealerMsisdn
296
                ),
297
                [
298
                    'headers' => [
299
                        'Authorization' => sprintf(
300
                            'Bearer %s',
301
                            $this->options['token']
302
                        ),
303
                    ],
304
                    'json'    => [
305
                        'smartloadId' => $dealerMsisdn,
306
                        'startDate'   => $start,
0 ignored issues
show
Bug introduced by
The variable $start does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
307
                        'endDate'     => $end,
0 ignored issues
show
Bug introduced by
The variable $end does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
308
                    ],
309
                ]
310
            );
311
312
            return [
313
                'status'    => 'ok',
314
                'http_code' => $response->getStatusCode(),
315
                'body'      => (string) $response->getBody(),
316
            ];
317
        } catch (\GuzzleHttp\Exception\ClientException $e) {
318
            return $this->clientError($e);
319
        } catch (\GuzzleHttp\Exception\ServerException $e) {
320
            return $this->parseError($e);
321
        }
322
    }
323
324
    /**
325
     * Authenticate and retrieves a list of all available networks.
326
     *
327
     * @throws Exception
328
     *
329
     * @return array
330
     */
331 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...
332
    {
333
        try {
334 2
            $response = $this->get(
335 2
                sprintf(
336 2
                    '/webservice/smartload/networks/%d',
337 2
                    $id
338
                ),
339
                [
340
                    'headers' => [
341 2
                        'Authorization' => sprintf(
342 2
                            'Bearer %s',
343 2
                            $this->options['token']
344
                        ),
345
                    ],
346
                ]
347
            );
348
349
            return [
350 1
                'status'    => 'ok',
351 1
                'http_code' => $response->getStatusCode(),
352 1
                'body'      => (string) $response->getBody(),
353
            ];
354 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
355 1
            return $this->clientError($e);
356
        } catch (\GuzzleHttp\Exception\ServerException $e) {
357
            return $this->parseError($e);
358
        }
359
    }
360
361
    /**
362
     * Authenticate and retrieves a list of all available networks.
363
     *
364
     * @throws Exception
365
     *
366
     * @return array
367
     */
368 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...
369
    {
370
        try {
371 2
            $response = $this->get(
372 2
                '/webservice/smartload/networks',
373
                [
374
                    'headers' => [
375 2
                        'Authorization' => sprintf(
376 2
                            'Bearer %s',
377 2
                            $this->options['token']
378
                        ),
379
                    ],
380
                ]
381
            );
382
383
            return [
384 1
                'status'    => 'ok',
385 1
                'http_code' => $response->getStatusCode(),
386 1
                'body'      => (string) $response->getBody(),
387
            ];
388 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
389 1
            return $this->clientError($e);
390
        } catch (\GuzzleHttp\Exception\ServerException $e) {
391
            return $this->parseError($e);
392
        }
393
    }
394
395
    /**
396
     * Test SmartCall is responding.
397
     *
398
     * @throws Exception
399
     *
400
     * @return array
401
     */
402 1
    public function ping()
403
    {
404
        try {
405 1
            $response = $this->get(
406 1
                '/webservice/test/ping'
407
            );
408
409
            return [
410 1
                'status'    => 'ok',
411 1
                'http_code' => $response->getStatusCode(),
412 1
                'body'      => (string) $response->getBody(),
413
            ];
414
        } catch (\GuzzleHttp\Exception\ClientException $e) {
415
            return $this->clientError($e);
416
        } catch (\GuzzleHttp\Exception\ServerException $e) {
417
            return $this->parseError($e);
418
        }
419
    }
420
421
    /**
422
     * Authenticate and retrieves a list of all available networks.
423
     *
424
     * @throws Exception
425
     *
426
     * @return array
427
     */
428 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...
429
    {
430
        try {
431 2
            $response = $this->get(
432 2
                sprintf(
433 2
                    '/webservice/smartload/products/%d',
434 2
                    $id
435
                ),
436
                [
437
                    'headers' => [
438 2
                        'Authorization' => sprintf(
439 2
                            'Bearer %s',
440 2
                            $this->options['token']
441
                        ),
442
                    ],
443
                ]
444
            );
445
446
            return [
447 1
                'status'    => 'ok',
448 1
                'http_code' => $response->getStatusCode(),
449 1
                'body'      => (string) $response->getBody(),
450
            ];
451 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
452 1
            return $this->clientError($e);
453
        } catch (\GuzzleHttp\Exception\ServerException $e) {
454
            return $this->parseError($e);
455
        }
456
    }
457
458
    /**
459
     * Parse the java exception that we receive from Smartcall's Tomcat's.
460
     *
461
     * @param \GuzzleHttp\Exception\ServerException $exception
462
     *
463
     * @return array
464
     */
465 8 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...
466
    {
467 8
        $body = (string) $exception->getResponse()->getBody();
468
469
        return [
470 8
            'status'    => 'error',
471 8
            'http_code' => $exception->getResponse()->getStatusCode(),
472 8
            'body'      => json_decode($body),
473
        ];
474
    }
475
476
    /**
477
     * Parse the java exception that we receive from Smartcall's Tomcat's.
478
     *
479
     * @param \GuzzleHttp\Exception\ServerException $exception
480
     *
481
     * @return array
482
     */
483 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...
484
    {
485
        $body = (string) $exception->getResponse()->getBody();
486
        preg_match('!<p><b>type</b> Exception report</p><p><b>message</b> <u>(.*[^</u>])</u></p><p><b>description</b>!', $body, $matches);
487
        return [
488
            'status'    => 'error',
489
            'http_code' => $exception->getResponse()->getStatusCode(),
490
            'body'      => $matches['1'],
491
        ];
492
    }
493
}
494