Passed
Push — master ( 2aa446...1ea355 )
by Evgeniy
02:12
created

PrepareJsonDataTrait::prepareJsonData()   B

Complexity

Conditions 10
Paths 7

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 10

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 17
cts 17
cp 1
crap 10
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 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