Passed
Push — master ( d11e33...2ee145 )
by Jacques
01:53
created

Client::balance()   B

Complexity

Conditions 3
Paths 5

Size

Total Lines 29
Code Lines 18

Duplication

Lines 29
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 29
loc 29
ccs 0
cts 15
cp 0
rs 8.8571
cc 3
eloc 18
nc 5
nop 1
crap 12
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 array $options
39
     */
40 20
    public function __construct($options = [])
41
    {
42
        /*
43
         * Allow on instantiation to overwrite the defaults
44
         */
45 20
        $this->options = array_merge(
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 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...
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 retrieves the dealer balance in Rands.
264
     *
265
     * @param string $dealerMsisdn
266
     *
267
     * @throws Exception
268
     *
269
     * @return array
270
     */
271 View Code Duplication
    public function balance($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/balance/%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
     * Authenticate and request current day cashup report.
302
     *
303
     * @param string $dealerMsisdn
304
     *
305
     * @throws Exception
306
     *
307
     * @return array
308
     */
309 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...
310
    {
311
        try {
312
            $response = $this->get(
313
                sprintf(
314
                    '/webservice/smartload/cashup/%s',
315
                    $dealerMsisdn
316
                ),
317
                [
318
                    'headers' => [
319
                        'Authorization' => sprintf(
320
                            'Bearer %s',
321
                            $this->options['token']
322
                        ),
323
                    ],
324
                ]
325
            );
326
327
            return [
328
                'status'    => 'ok',
329
                'http_code' => $response->getStatusCode(),
330
                'body'      => (string) $response->getBody(),
331
            ];
332
        } catch (\GuzzleHttp\Exception\ClientException $e) {
333
            return $this->clientError($e);
334
        } catch (\GuzzleHttp\Exception\ServerException $e) {
335
            return $this->parseError($e);
336
        }
337
    }
338
339
    /**
340
     * Authenticate and request to transfer funds from one Smartload account to another.
341
     *
342
     * @param string $fromDealerMsisdn
343
     * @param string $toDealerMsisdn
344
     * @param string $amount
345
     * @param string $sendSms
346
     *
347
     * @throws Exception
348
     *
349
     * @return array
350
     */
351 View Code Duplication
    public function fundstransfer($fromDealerMsisdn, $toDealerMsisdn, $amount, $sendSms)
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...
352
    {
353
        try {
354
            $response = $this->post(
355
                '/webservice/smartload/fundstransfer',
356
                [
357
                    'headers' => [
358
                        'Authorization' => sprintf(
359
                            'Bearer %s',
360
                            $this->options['token']
361
                        ),
362
                    ],
363
                    'json' => [
364
                        'sourceSmartloadId'    => $fromDealerMsisdn,
365
                        'recipientSmartloadId' => $toDealerMsisdn,
366
                        'amount'               => $amount,
367
                        'sendSms'              => $sendSms,
368
                    ],
369
                ]
370
            );
371
372
            return [
373
                'status'    => 'ok',
374
                'http_code' => $response->getStatusCode(),
375
                'body'      => (string) $response->getBody(),
376
            ];
377
        } catch (\GuzzleHttp\Exception\ClientException $e) {
378
            return $this->clientError($e);
379
        } catch (\GuzzleHttp\Exception\ServerException $e) {
380
            return $this->parseError($e);
381
        }
382
    }
383
384
    /**
385
     * Authenticate and retrieves a list of all available networks.
386
     *
387
     * @throws Exception
388
     *
389
     * @return array
390
     */
391 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...
392
    {
393
        try {
394 2
            $response = $this->get(
395 2
                sprintf(
396 2
                    '/webservice/smartload/networks/%d',
397 2
                    $id
398
                ),
399
                [
400
                    'headers' => [
401 2
                        'Authorization' => sprintf(
402 2
                            'Bearer %s',
403 2
                            $this->options['token']
404
                        ),
405
                    ],
406
                ]
407
            );
408
409
            return [
410 1
                'status'    => 'ok',
411 1
                'http_code' => $response->getStatusCode(),
412 1
                'body'      => (string) $response->getBody(),
413
            ];
414 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
415 1
            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 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...
429
    {
430
        try {
431 2
            $response = $this->get(
432 2
                '/webservice/smartload/networks',
433
                [
434
                    'headers' => [
435 2
                        'Authorization' => sprintf(
436 2
                            'Bearer %s',
437 2
                            $this->options['token']
438
                        ),
439
                    ],
440
                ]
441
            );
442
443
            return [
444 1
                'status'    => 'ok',
445 1
                'http_code' => $response->getStatusCode(),
446 1
                'body'      => (string) $response->getBody(),
447
            ];
448 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
449 1
            return $this->clientError($e);
450
        } catch (\GuzzleHttp\Exception\ServerException $e) {
451
            return $this->parseError($e);
452
        }
453
    }
454
455
    /**
456
     * Test SmartCall is responding.
457
     *
458
     * @throws Exception
459
     *
460
     * @return array
461
     */
462 1
    public function ping()
463
    {
464
        try {
465 1
            $response = $this->get(
466 1
                '/webservice/test/ping'
467
            );
468
469
            return [
470 1
                'status'    => 'ok',
471 1
                'http_code' => $response->getStatusCode(),
472 1
                'body'      => (string) $response->getBody(),
473
            ];
474
        } catch (\GuzzleHttp\Exception\ClientException $e) {
475
            return $this->clientError($e);
476
        } catch (\GuzzleHttp\Exception\ServerException $e) {
477
            return $this->parseError($e);
478
        }
479
    }
480
481
    /**
482
     * Authenticate and retrieves a list of all available networks.
483
     *
484
     * @throws Exception
485
     *
486
     * @return array
487
     */
488 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...
489
    {
490
        try {
491 2
            $response = $this->get(
492 2
                sprintf(
493 2
                    '/webservice/smartload/products/%d',
494 2
                    $id
495
                ),
496
                [
497
                    'headers' => [
498 2
                        'Authorization' => sprintf(
499 2
                            'Bearer %s',
500 2
                            $this->options['token']
501
                        ),
502
                    ],
503
                ]
504
            );
505
506
            return [
507 1
                'status'    => 'ok',
508 1
                'http_code' => $response->getStatusCode(),
509 1
                'body'      => (string) $response->getBody(),
510
            ];
511 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
512 1
            return $this->clientError($e);
513
        } catch (\GuzzleHttp\Exception\ServerException $e) {
514
            return $this->parseError($e);
515
        }
516
    }
517
518
    /**
519
     * Authenticate and checks if the provided ID (MSISDN) is registered with Smartload.
520
     *
521
     * @param string $dealerMsisdn
522
     *
523
     * @throws Exception
524
     *
525
     * @return array
526
     */
527 View Code Duplication
    public function registered($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...
528
    {
529
        try {
530
            $response = $this->get(
531
                sprintf(
532
                    '/webservice/smartload/registered/%s',
533
                    $dealerMsisdn
534
                ),
535
                [
536
                    'headers' => [
537
                        'Authorization' => sprintf(
538
                            'Bearer %s',
539
                            $this->options['token']
540
                        ),
541
                    ],
542
                ]
543
            );
544
545
            return [
546
                'status'    => 'ok',
547
                'http_code' => $response->getStatusCode(),
548
                'body'      => (string) $response->getBody(),
549
            ];
550
        } catch (\GuzzleHttp\Exception\ClientException $e) {
551
            return $this->clientError($e);
552
        } catch (\GuzzleHttp\Exception\ServerException $e) {
553
            return $this->parseError($e);
554
        }
555
    }
556
557
    /**
558
     * Parse the java exception that we receive from Smartcall's Tomcat's.
559
     *
560
     * @param \GuzzleHttp\Exception\ClientException $exception
561
     *
562
     * @return array
563
     */
564 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...
565
    {
566 9
        $body = (string) $exception->getResponse()->getBody();
567
568
        return [
569 9
            'status'    => 'error',
570 9
            'http_code' => $exception->getResponse()->getStatusCode(),
571 9
            'body'      => json_decode($body),
572
        ];
573
    }
574
575
    /**
576
     * Parse the java exception that we receive from Smartcall's Tomcat's.
577
     *
578
     * @param \GuzzleHttp\Exception\ServerException $exception
579
     *
580
     * @return array
581
     */
582 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...
583
    {
584
        $body = (string) $exception->getResponse()->getBody();
585
        preg_match('!<p><b>type</b> Exception report</p><p><b>message</b> <u>(.*[^</u>])</u></p><p><b>description</b>!', $body, $matches);
586
587
        return [
588
            'status'    => 'error',
589
            'http_code' => $exception->getResponse()->getStatusCode(),
590
            'body'      => $matches['1'],
591
        ];
592
    }
593
594
    /**
595
     * Use basic authentication header content if bearer token  is not set.
596
     *
597
     * @param string $username
598
     * @param string $password
599
     *
600
     * @return string
601
     */
602 6
    private function bearerOrBasic($username = null, $password = null)
603
    {
604 6
        if (is_null($username)) {
605 2
            return sprintf(
606 2
                'Bearer %s',
607 2
                $this->options['token']
608
            );
609
        }
610
611 4
        return sprintf(
612 4
            'Basic %s',
613 4
            base64_encode(
614 4
                sprintf(
615 4
                    '%s:%s',
616 4
                    $username,
617 4
                    $password
618
                )
619
            )
620
        );
621
    }
622
}
623