Generic::call()   A
last analyzed

Complexity

Conditions 5
Paths 14

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 17
c 2
b 0
f 0
dl 0
loc 28
ccs 0
cts 19
cp 0
rs 9.3888
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 $params): ?string
13
    {
14
        $params['new_session'] = true === $params['new_session'] ? 'yes' : 'no';
15
16
        try {
17
            $response = (new Client())->request('POST', $uri, [
18
                'headers' => [
19
                    'Accept' => 'application/json',
20
                ],
21
                'json' => $params,
22
            ]);
23
24
            $body = json_decode((string) $response->getBody());
25
26
            if ('break' === $body->flow) {
27
                throw new \Exception($body->data);
28
            }
29
        } catch (RequestException $ex) {
30
            $response = $ex->getResponse();
31
            $body = json_decode((string) $response->getBody());
32
            $message = $body->message ?? $response->getReasonPhrase();
33
34
            throw new \Exception(sprintf('%s . %s', $message, $response->getStatusCode()));
35
        } catch (TransferException $ex) {
36
            throw new \Exception(sprintf('%s . %s', $ex->getMessage(), $ex->getCode()));
37
        }
38
39
        return $body->data;
40
    }
41
}
42