PrepareJsonDataTrait   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 42
ccs 17
cts 17
cp 1
rs 10
wmc 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B prepareJsonData() 0 32 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace HttpSoft\Basis\Response;
6
7
use DateTimeInterface;
8
use JsonSerializable;
9
use stdClass;
10
11
use function is_array;
12
use function is_object;
13
14
trait PrepareJsonDataTrait
15
{
16
    /**
17
     * Pre-processes the data before sending it to `json_encode()`.
18
     *
19
     * @param mixed $data data to be pre-processed.
20
     * @return mixed pre-processed data.
21
     * @psalm-suppress MixedArrayOffset
22
     * @psalm-suppress MixedAssignment
23
     */
24 18
    private function prepareJsonData($data)
25
    {
26 18
        if (is_object($data)) {
27 7
            if ($data instanceof JsonSerializable) {
28 1
                return $this->prepareJsonData($data->jsonSerialize());
29
            }
30
31 6
            if ($data instanceof DateTimeInterface) {
32 1
                return $this->prepareJsonData((array) $data);
33
            }
34
35 5
            $object = $data;
36 5
            $data = [];
37
38 5
            foreach ($object as $name => $value) {
39 4
                $data[$name] = $value;
40
            }
41
42 5
            if ($data === []) {
43 4
                return new stdClass();
44
            }
45
        }
46
47 18
        if (is_array($data)) {
48 17
            foreach ($data as $key => $value) {
49 16
                if (is_array($value) || is_object($value)) {
50 6
                    $data[$key] = $this->prepareJsonData($value);
51
                }
52
            }
53
        }
54
55 18
        return $data;
56
    }
57
}
58