Passed
Push — next ( 147fd5...b42a44 )
by Bas
03:36 queued 01:41
created

HandlesJson   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 49
ccs 17
cts 18
cp 0.9444
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A decodeResponse() 0 16 3
A jsonEncode() 0 14 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ArangoClient;
6
7
use ArangoClient\Exceptions\ArangoException;
8
use GuzzleHttp\Psr7\StreamWrapper;
9
use JsonMachine\JsonDecoder\ExtJsonDecoder;
10
use JsonMachine\JsonMachine;
11
use Psr\Http\Message\ResponseInterface;
12
use stdClass;
13
14
trait HandlesJson
15
{
16
17
18
    /**
19
     * @param  mixed  $data
20
     * @return string
21
     * @throws ArangoException
22
     */
23 72
    public function jsonEncode(mixed $data): string
24
    {
25 72
        $options = 0;
26 72
        if (empty($data)) {
27 3
            $options = JSON_FORCE_OBJECT;
28
        }
29
30 72
        $response = json_encode($data, $options);
31
32 72
        if ($response === false) {
33 1
            throw new ArangoException('JSON encoding failed with error: ' . json_last_error_msg(), json_last_error());
34
        }
35
36 71
        return $response;
37
    }
38
39
40
    /**
41
     * @psalm-suppress MixedAssignment, MixedArrayOffset
42
     * @SuppressWarnings(PHPMD.StaticAccess)
43
     *
44
     * @param  ResponseInterface|null  $response
45
     * @return stdClass
46
     */
47 105
    protected function decodeResponse(?ResponseInterface $response): stdClass
48
    {
49 105
        $decodedResponse = new stdClass();
50 105
        if (! isset($response)) {
51
            return $decodedResponse;
52
        }
53
54 105
        $phpStream = StreamWrapper::getResource($response->getBody());
55 105
        $decoder = new ExtJsonDecoder(false);
56 105
        $decodedStream = JsonMachine::fromStream($phpStream, '', $decoder);
57
58 105
        foreach ($decodedStream as $key => $value) {
59 105
            $decodedResponse->$key = $value;
60
        }
61
62 105
        return $decodedResponse;
63
    }
64
}
65