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

Generic::call()   A

Complexity

Conditions 5
Paths 14

Size

Total Lines 35
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 35
ccs 0
cts 20
cp 0
rs 9.2408
cc 5
nc 14
nop 2
crap 30
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 Generic implements Aggregator
11
{
12
    public function call(string $uri, array $simulator): ?string
13
    {
14
        $params = [
15
            'new_session' => true === $simulator['new_session'] ? 'yes' : 'no',
16
            'session_id' => $simulator['session_id'],
17
            'network_code' => $simulator['network_code'],
18
            'phone_number' => $simulator['phone_number'],
19
            'input' => $simulator['input'],
20
            'service_code' => $simulator['service_code'],
21
        ];
22
23
        try {
24
            $response = (new Client())->request('POST', $uri, [
25
                'headers' => [
26
                    'Accept' => 'application/json',
27
                ],
28
                'json' => $params,
29
            ]);
30
31
            $body = json_decode((string) $response->getBody());
32
33
            if ('break' === $body->flow) {
34
                throw new \Exception($body->data);
35
            }
36
        } catch (RequestException $ex) {
37
            $response = $ex->getResponse();
38
            $body = json_decode((string) $response->getBody());
39
            $message = $body->message ?? $response->getReasonPhrase();
40
41
            throw new \Exception(sprintf('%s . %s', $message, $response->getStatusCode()));
42
        } catch (TransferException $ex) {
43
            throw new \Exception(sprintf('%s . %s', $ex->getMessage(), $ex->getCode()));
44
        }
45
46
        return $body->data;
47
    }
48
}
49