Passed
Push — master ( aa9fc0...2aa446 )
by Evgeniy
06:56
created

PrepareJsonDataTrait::prepareJsonData()   B

Complexity

Conditions 10
Paths 7

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 10.1626

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 16
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 32
ccs 15
cts 17
cp 0.8824
crap 10.1626
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 12
    private function prepareJsonData($data)
25
    {
26 12
        if (is_object($data)) {
27 3
            if ($data instanceof JsonSerializable) {
28
                return $this->prepareJsonData($data->jsonSerialize());
29
            }
30
31 3
            if ($data instanceof DateTimeInterface) {
32
                return $this->prepareJsonData((array) $data);
33
            }
34
35 3
            $object = $data;
36 3
            $data = [];
37
38 3
            foreach ($object as $name => $value) {
39 3
                $data[$name] = $value;
40
            }
41
42 3
            if ($data === []) {
43 3
                return new stdClass();
44
            }
45
        }
46
47 12
        if (is_array($data)) {
48 12
            foreach ($data as $key => $value) {
49 12
                if (is_array($value) || is_object($value)) {
50 6
                    $data[$key] = $this->prepareJsonData($value);
51
                }
52
            }
53
        }
54
55 12
        return $data;
56
    }
57
}
58