Passed
Push — master ( faa71e...73327e )
by Jacques
01:58
created

Client::products()   B

Complexity

Conditions 3
Paths 5

Size

Total Lines 26
Code Lines 16

Duplication

Lines 26
Ratio 100 %

Code Coverage

Tests 11
CRAP Score 3.0327

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 26
loc 26
ccs 11
cts 13
cp 0.8462
rs 8.8571
cc 3
eloc 16
nc 5
nop 1
crap 3.0327
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
     * Set the password for basic authentication.
76
     *
77
     * @param string $password Password for use with basic authentication
0 ignored issues
show
Bug introduced by
There is no parameter named $password. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
78
     */
79
    public function setPassword($token)
0 ignored issues
show
Unused Code introduced by
The parameter $token is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
80
    {
81
        $this->options['password'] = $password;
0 ignored issues
show
Bug introduced by
The variable $password 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...
82
    }
83
84
    /**
85
     * Set the username for basic authentication.
86
     *
87
     * @param string $username Username for use with basic authentication
88
     */
89
    public function setUsername($username)
90
    {
91
        $this->options['username'] = $username;
92
    }
93
94
    /**
95
     * Authenticate and get Bearer token from SmartCall.
96
     *
97
     * @throws Exception
98
     *
99
     * @return array
100
     */
101 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...
102
    {
103
        try {
104 3
            $response = $this->post(
105 3
                '/webservice/auth',
106
                [
107
                    'headers' => [
108 3
                        'Authorization' => $this->bearerOrBasic(),
109
                    ],
110
                ]
111
            );
112
113
            return [
114 1
                'status'    => 'ok',
115 1
                'http_code' => $response->getStatusCode(),
116 1
                'body'      => (string) $response->getBody(),
117
            ];
118 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
119 2
            return $this->clientError($e);
120
        } catch (\GuzzleHttp\Exception\ServerException $e) {
121
            return $this->parseError($e);
122
        }
123
    }
124
125
    /**
126
     * Authenticate and invalidates all the user allocated tokens.
127
     *
128
     * @throws Exception
129
     *
130
     * @return array
131
     */
132 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...
133
    {
134
        try {
135 2
            $response = $this->delete(
136 2
                '/webservice/auth',
137
                [
138
                    'headers' => [
139 2
                        'Authorization' => $this->bearerOrBasic(),
140
                    ],
141
                ]
142
            );
143
144
            return [
145 1
                'status'    => 'ok',
146 1
                'http_code' => $response->getStatusCode(),
147 1
                'body'      => (string) $response->getBody(),
148
            ];
149 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
150 1
            return $this->clientError($e);
151
        } catch (\GuzzleHttp\Exception\ServerException $e) {
152
            return $this->parseError($e);
153
        }
154
    }
155
156
    /**
157
     * Authenticate and invalidates all the user allocated tokens.
158
     *
159
     * @throws Exception
160
     *
161
     * @return array
162
     */
163 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...
164
    {
165
        try {
166 3
            $response = $this->delete(
167 3
                '/webservice/auth/token',
168
                [
169
                    'headers' => [
170 3
                        'Authorization' => $this->bearerOrBasic(),
171
                    ],
172
                ]
173
            );
174
175
            return [
176 2
                'status'    => 'ok',
177 2
                'http_code' => $response->getStatusCode(),
178 2
                'body'      => (string) $response->getBody(),
179
            ];
180 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
181 1
            return $this->clientError($e);
182
        } catch (\GuzzleHttp\Exception\ServerException $e) {
183
            return $this->parseError($e);
184
        }
185
    }
186
187
    /**
188
     * Authenticate and gets the number of available session tokens.
189
     *
190
     * @throws Exception
191
     *
192
     * @return array
193
     */
194 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...
195
    {
196
        try {
197 3
            $response = $this->get(
198 3
                '/webservice/auth/token',
199
                [
200
                    'headers' => [
201 3
                        'Authorization' => $this->bearerOrBasic(),
202
                    ],
203
                ]
204
            );
205
206
            return [
207 1
                'status'    => 'ok',
208 1
                'http_code' => $response->getStatusCode(),
209 1
                'body'      => (string) $response->getBody(),
210
            ];
211 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
212 2
            return $this->clientError($e);
213
        } catch (\GuzzleHttp\Exception\ServerException $e) {
214
            return $this->parseError($e);
215
        }
216
    }
217
218
    /**
219
     * Authenticate and request period based cashup reports.
220
     *
221
     * @param string $dealerMsisdn
222
     * @param string $start
223
     * @param string $end
224
     *
225
     * @throws Exception
226
     *
227
     * @return array
228
     */
229 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...
230
    {
231
        try {
232
            $response = $this->post(
233
                '/webservice/smartload/cashup',
234
                [
235
                    'headers' => [
236
                        'Authorization' => $this->bearerOrBasic(),
237
                    ],
238
                    'json'    => [
239
                        'smartloadId' => $dealerMsisdn,
240
                        'startDate'   => $start,
241
                        'endDate'     => $end,
242
                    ],
243
                ]
244
            );
245
246
            return [
247
                'status'    => 'ok',
248
                'http_code' => $response->getStatusCode(),
249
                'body'      => (string) $response->getBody(),
250
            ];
251
        } catch (\GuzzleHttp\Exception\ClientException $e) {
252
            return $this->clientError($e);
253
        } catch (\GuzzleHttp\Exception\ServerException $e) {
254
            return $this->parseError($e);
255
        }
256
    }
257
258
    /**
259
     * Authenticate and retrieves the dealer balance in Rands.
260
     *
261
     * @param string $dealerMsisdn
262
     *
263
     * @throws Exception
264
     *
265
     * @return array
266
     */
267 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...
268
    {
269
        try {
270
            $response = $this->get(
271
                sprintf(
272
                    '/webservice/smartload/balance/%s',
273
                    $dealerMsisdn
274
                ),
275
                [
276
                    'headers' => [
277
                        'Authorization' => $this->bearerOrBasic(),
278
                    ],
279
                ]
280
            );
281
282
            return [
283
                'status'    => 'ok',
284
                'http_code' => $response->getStatusCode(),
285
                'body'      => (string) $response->getBody(),
286
            ];
287
        } catch (\GuzzleHttp\Exception\ClientException $e) {
288
            return $this->clientError($e);
289
        } catch (\GuzzleHttp\Exception\ServerException $e) {
290
            return $this->parseError($e);
291
        }
292
    }
293
294
    /**
295
     * Authenticate and request current day cashup report.
296
     *
297
     * @param string $dealerMsisdn
298
     *
299
     * @throws Exception
300
     *
301
     * @return array
302
     */
303 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...
304
    {
305
        try {
306
            $response = $this->get(
307
                sprintf(
308
                    '/webservice/smartload/cashup/%s',
309
                    $dealerMsisdn
310
                ),
311
                [
312
                    'headers' => [
313
                        'Authorization' => $this->bearerOrBasic(),
314
                    ],
315
                ]
316
            );
317
318
            return [
319
                'status'    => 'ok',
320
                'http_code' => $response->getStatusCode(),
321
                'body'      => (string) $response->getBody(),
322
            ];
323
        } catch (\GuzzleHttp\Exception\ClientException $e) {
324
            return $this->clientError($e);
325
        } catch (\GuzzleHttp\Exception\ServerException $e) {
326
            return $this->parseError($e);
327
        }
328
    }
329
330
    /**
331
     * Authenticate and request to transfer funds from one Smartload account to another.
332
     *
333
     * @param string $fromDealerMsisdn
334
     * @param string $toDealerMsisdn
335
     * @param string $amount
336
     * @param string $sendSms
337
     *
338
     * @throws Exception
339
     *
340
     * @return array
341
     */
342 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...
343
    {
344
        try {
345
            $response = $this->post(
346
                '/webservice/smartload/fundstransfer',
347
                [
348
                    'headers' => [
349
                        'Authorization' => $this->bearerOrBasic(),
350
                    ],
351
                    'json' => [
352
                        'sourceSmartloadId'    => $fromDealerMsisdn,
353
                        'recipientSmartloadId' => $toDealerMsisdn,
354
                        'amount'               => $amount,
355
                        'sendSms'              => $sendSms,
356
                    ],
357
                ]
358
            );
359
360
            return [
361
                'status'    => 'ok',
362
                'http_code' => $response->getStatusCode(),
363
                'body'      => (string) $response->getBody(),
364
            ];
365
        } catch (\GuzzleHttp\Exception\ClientException $e) {
366
            return $this->clientError($e);
367
        } catch (\GuzzleHttp\Exception\ServerException $e) {
368
            return $this->parseError($e);
369
        }
370
    }
371
372
    /**
373
     * Authenticate and retrieves a list of all available networks.
374
     *
375
     * @throws Exception
376
     *
377
     * @return array
378
     */
379 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...
380
    {
381
        try {
382 2
            $response = $this->get(
383 2
                sprintf(
384 2
                    '/webservice/smartload/networks/%d',
385 2
                    $id
386
                ),
387
                [
388
                    'headers' => [
389 2
                        'Authorization' => $this->bearerOrBasic(),
390
                    ],
391
                ]
392
            );
393
394
            return [
395 1
                'status'    => 'ok',
396 1
                'http_code' => $response->getStatusCode(),
397 1
                'body'      => (string) $response->getBody(),
398
            ];
399 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
400 1
            return $this->clientError($e);
401
        } catch (\GuzzleHttp\Exception\ServerException $e) {
402
            return $this->parseError($e);
403
        }
404
    }
405
406
    /**
407
     * Authenticate and retrieves a list of all available networks.
408
     *
409
     * @throws Exception
410
     *
411
     * @return array
412
     */
413 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...
414
    {
415
        try {
416 2
            $response = $this->get(
417 2
                '/webservice/smartload/networks',
418
                [
419
                    'headers' => [
420 2
                        'Authorization' => $this->bearerOrBasic(),
421
                    ],
422
                ]
423
            );
424
425
            return [
426 1
                'status'    => 'ok',
427 1
                'http_code' => $response->getStatusCode(),
428 1
                'body'      => (string) $response->getBody(),
429
            ];
430 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
431 1
            return $this->clientError($e);
432
        } catch (\GuzzleHttp\Exception\ServerException $e) {
433
            return $this->parseError($e);
434
        }
435
    }
436
437
    /**
438
     * Test SmartCall is responding.
439
     *
440
     * @throws Exception
441
     *
442
     * @return array
443
     */
444 1
    public function ping()
445
    {
446
        try {
447 1
            $response = $this->get(
448 1
                '/webservice/test/ping'
449
            );
450
451
            return [
452 1
                'status'    => 'ok',
453 1
                'http_code' => $response->getStatusCode(),
454 1
                'body'      => (string) $response->getBody(),
455
            ];
456
        } catch (\GuzzleHttp\Exception\ClientException $e) {
457
            return $this->clientError($e);
458
        } catch (\GuzzleHttp\Exception\ServerException $e) {
459
            return $this->parseError($e);
460
        }
461
    }
462
463
    /**
464
     * Authenticate and retrieves a list of all available networks.
465
     *
466
     * @throws Exception
467
     *
468
     * @return array
469
     */
470 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...
471
    {
472
        try {
473 2
            $response = $this->get(
474 2
                sprintf(
475 2
                    '/webservice/smartload/products/%d',
476 2
                    $id
477
                ),
478
                [
479
                    'headers' => [
480 2
                        'Authorization' => $this->bearerOrBasic(),
481
                    ],
482
                ]
483
            );
484
485
            return [
486 1
                'status'    => 'ok',
487 1
                'http_code' => $response->getStatusCode(),
488 1
                'body'      => (string) $response->getBody(),
489
            ];
490 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
491 1
            return $this->clientError($e);
492
        } catch (\GuzzleHttp\Exception\ServerException $e) {
493
            return $this->parseError($e);
494
        }
495
    }
496
497
    /**
498
     * Authenticate and checks if the provided ID (MSISDN) is registered with Smartload.
499
     *
500
     * @param string $dealerMsisdn
501
     *
502
     * @throws Exception
503
     *
504
     * @return array
505
     */
506 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...
507
    {
508
        try {
509
            $response = $this->get(
510
                sprintf(
511
                    '/webservice/smartload/registered/%s',
512
                    $dealerMsisdn
513
                ),
514
                [
515
                    'headers' => [
516
                        'Authorization' => $this->bearerOrBasic(),
517
                    ],
518
                ]
519
            );
520
521
            return [
522
                'status'    => 'ok',
523
                'http_code' => $response->getStatusCode(),
524
                'body'      => (string) $response->getBody(),
525
            ];
526
        } catch (\GuzzleHttp\Exception\ClientException $e) {
527
            return $this->clientError($e);
528
        } catch (\GuzzleHttp\Exception\ServerException $e) {
529
            return $this->parseError($e);
530
        }
531
    }
532
533
    /**
534
     * Parse the java exception that we receive from Smartcall's Tomcat's.
535
     *
536
     * @param \GuzzleHttp\Exception\ClientException $exception
537
     *
538
     * @return array
539
     */
540 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...
541
    {
542 9
        $body = (string) $exception->getResponse()->getBody();
543
544
        return [
545 9
            'status'    => 'error',
546 9
            'http_code' => $exception->getResponse()->getStatusCode(),
547 9
            'body'      => json_decode($body),
548
        ];
549
    }
550
551
    /**
552
     * Parse the java exception that we receive from Smartcall's Tomcat's.
553
     *
554
     * @param \GuzzleHttp\Exception\ServerException $exception
555
     *
556
     * @return array
557
     */
558 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...
559
    {
560
        $body = (string) $exception->getResponse()->getBody();
561
        preg_match('!<p><b>type</b> Exception report</p><p><b>message</b> <u>(.*[^</u>])</u></p><p><b>description</b>!', $body, $matches);
562
563
        return [
564
            'status'    => 'error',
565
            'http_code' => $exception->getResponse()->getStatusCode(),
566
            'body'      => $matches['1'],
567
        ];
568
    }
569
570
    /**
571
     * Use basic authentication header content if bearer token  is not set.
572
     *
573
     * @param string $username
574
     * @param string $password
575
     *
576
     * @return string
577
     */
578 17
    private function bearerOrBasic($username = null, $password = null)
0 ignored issues
show
Unused Code introduced by
The parameter $username is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $password is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
579
    {
580
        /**
581
         * Get the function calling this method.
582
         */
583 17
        $caller = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2)[1]['function'];
584
585
        if (
586 17
            !in_array(
587 17
                $caller,
588
                [
589 17
                    'auth',
590
                ]
591
            )
592
        ) {
593 14
            return sprintf(
594 14
                'Bearer %s',
595 14
                $this->options['token']
596
            );
597
        }
598
599 3
        return sprintf(
600 3
            'Basic %s',
601 3
            base64_encode(
602 3
                sprintf(
603 3
                    '%s:%s',
604 3
                    $this->options['username'],
605 3
                    $this->options['password']
606
                )
607
            )
608
        );
609
    }
610
}
611