Issues (24)

src/HandlesJson.php (1 issue)

Labels
Severity
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\Items;
10
use JsonMachine\JsonDecoder\ExtJsonDecoder;
11
use Psr\Http\Message\ResponseInterface;
12
use stdClass;
13
14
trait HandlesJson
15
{
16
    /**
17
     * @throws ArangoException
18
     */
19 79
    public function jsonEncode(mixed $data): string
20
    {
21 79
        $options = 0;
22 79
        if (empty($data)) {
23 3
            $options = JSON_FORCE_OBJECT;
24
        }
25
26 79
        $response = json_encode($data, $options);
27
28 79
        if ($response === false) {
29 1
            throw new ArangoException('JSON encoding failed with error: ' . json_last_error_msg(), json_last_error());
30
        }
31
32 78
        return $response;
33
    }
34
35
    /**
36
     * @SuppressWarnings(PHPMD.StaticAccess)
37
     */
38 117
    protected function decodeJsonResponse(ResponseInterface $response): stdClass
39
    {
40 117
        $contentLength = $response->getHeaderLine('Content-Length');
41 117
        $sizeSwitch = $this->getConfig('jsonStreamDecoderThreshold');
0 ignored issues
show
It seems like getConfig() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

41
        /** @scrutinizer ignore-call */ 
42
        $sizeSwitch = $this->getConfig('jsonStreamDecoderThreshold');
Loading history...
42 117
        if ($contentLength < $sizeSwitch) {
43 117
            return json_decode($response->getBody()->getContents(), false, 512, JSON_THROW_ON_ERROR);
44
        }
45
46
        $decodedResponse = new stdClass();
47
48
        $phpStream = StreamWrapper::getResource($response->getBody());
49
        $decoder = new ExtJsonDecoder(true);
50
        $decodedStream = Items::fromStream($phpStream, ['decoder' => $decoder]);
51
52
        foreach ($decodedStream as $key => $value) {
53
            $decodedResponse->$key = $value;
54
        }
55
56
        return $decodedResponse;
57
    }
58
}
59