Passed
Push — master ( 5363e5...ff3cde )
by Brian
02:36
created

Africastalking::call()   A

Complexity

Conditions 4
Paths 11

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 34
ccs 0
cts 20
cp 0
rs 9.568
cc 4
nc 11
nop 2
crap 20
1
<?php
2
3
namespace Bmatovu\Ussd\Simulator;
4
5
use Bmatovu\Ussd\Contracts\Aggregator;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Exception\RequestException;
8
use GuzzleHttp\Exception\TransferException;
9
10
class Africastalking implements Aggregator
11
{
12
    public function call(string $uri, array $simulator): ?string
13
    {
14
        $params = [
15
            'sessionId' => $simulator['session_id'],
16
            'networkCode' => $simulator['network_code'],
17
            'phoneNumber' => $simulator['phone_number'],
18
            'text' => $simulator['answers'],
19
            'serviceCode' => $simulator['service_code'],
20
        ];
21
22
        try {
23
            $response = (new Client())->request('POST', $uri, [
24
                'form_params' => $params,
25
            ]);
26
27
            $body = (string) $response->getBody();
28
29
            $cmd = substr($body, 0, 3);
30
            $payload = substr($body, 4);
31
32
            if ('END' === $cmd) {
33
                throw new \Exception($payload);
34
            }
35
        } catch (RequestException $ex) {
36
            $response = $ex->getResponse();
37
            $body = (string) $response->getBody();
38
            $message = $body ?? $response->getReasonPhrase();
39
40
            throw new \Exception(sprintf('%s . %s', $message, $response->getStatusCode()));
41
        } catch (TransferException $ex) {
42
            throw new \Exception(sprintf('%s . %s', $ex->getMessage(), $ex->getCode()));
43
        }
44
45
        return $payload;
46
    }
47
}
48