Completed
Push — master ( 3e05ae...99069b )
by Asmir
12s
created

JsonSerializationVisitor::visitProperty()   C

Complexity

Conditions 10
Paths 6

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 10

Importance

Changes 0
Metric Value
cc 10
eloc 12
nc 6
nop 2
dl 0
loc 22
ccs 11
cts 11
cp 1
crap 10
rs 6.1368
c 0
b 0
f 0

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
/*
6
 * Copyright 2016 Johannes M. Schmitt <[email protected]>
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
namespace JMS\Serializer;
22
23
use JMS\Serializer\Exception\NotAcceptableException;
24
use JMS\Serializer\Exception\RuntimeException;
25
use JMS\Serializer\Metadata\ClassMetadata;
26
use JMS\Serializer\Metadata\PropertyMetadata;
27
use JMS\Serializer\Visitor\SerializationVisitorInterface;
28
29
final class JsonSerializationVisitor extends AbstractVisitor implements SerializationVisitorInterface
30
{
31
    private $options = JSON_PRESERVE_ZERO_FRACTION;
32
33
    private $dataStack = [];
34
    /**
35
     * @var \ArrayObject
36
     */
37
    private $data;
38
39 177
    public function __construct(
40
        int $options = JSON_PRESERVE_ZERO_FRACTION)
41
    {
42 177
        $this->dataStack = [];
43 177
        $this->options = $options;
44 177
    }
45
46 14
    public function visitNull($data, array $type)
47
    {
48 14
        return null;
49
    }
50
51 94
    public function visitString(string $data, array $type)
52
    {
53 94
        return $data;
54
    }
55
56 9
    public function visitBoolean(bool $data, array $type)
57
    {
58 9
        return $data;
59
    }
60
61 29
    public function visitInteger(int $data, array $type)
62
    {
63 29
        return $data;
64
    }
65
66 12
    public function visitDouble(float $data, array $type)
67
    {
68 12
        return $data;
69
    }
70
71
    /**
72
     * @param array $data
73
     * @param array $type
74
     * @return mixed
75
     */
76 81
    public function visitArray(array $data, array $type)
77
    {
78 81
        \array_push($this->dataStack, $data);
79
80 81
        $rs = isset($type['params'][1]) ? new \ArrayObject() : [];
81
82 81
        $isList = isset($type['params'][0]) && !isset($type['params'][1]);
83
84 81
        $elType = $this->getElementType($type);
85 81
        foreach ($data as $k => $v) {
86
87
            try {
88 73
                $v = $this->navigator->accept($v, $elType);
89 6
            } catch (NotAcceptableException $e) {
90 6
                continue;
91
            }
92
93 70
            if ($isList) {
94 19
                $rs[] = $v;
95
            } else {
96 70
                $rs[$k] = $v;
97
            }
98
        }
99
100 81
        \array_pop($this->dataStack);
101 81
        return $rs;
102
    }
103
104 94
    public function startVisitingObject(ClassMetadata $metadata, object $data, array $type): void
105
    {
106 94
        \array_push($this->dataStack, $this->data);
107 94
        $this->data = $metadata->isMap === true ? new \ArrayObject() : [];
0 ignored issues
show
Documentation Bug introduced by
It seems like $metadata->isMap === tru...ArrayObject() : array() can also be of type array. However, the property $data is declared as type ArrayObject. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
108 94
    }
109
110 93
    public function endVisitingObject(ClassMetadata $metadata, object $data, array $type)
111
    {
112 93
        $rs = $this->data;
113 93
        $this->data = \array_pop($this->dataStack);
114
115 93
        if ($metadata->isList !== true && empty($rs)) {
116 12
            return new \ArrayObject();
117
        }
118 86
        return $rs;
119
    }
120
121 87
    public function visitProperty(PropertyMetadata $metadata, $v): void
122
    {
123
        try {
124 87
            $v = $this->navigator->accept($v, $metadata->type);
125 4
        } catch (NotAcceptableException $e) {
126 4
            return;
127
        }
128
129 87
        if (true === $metadata->skipWhenEmpty && ($v instanceof \ArrayObject || \is_array($v)) && 0 === count($v)) {
130 2
            return;
131
        }
132
133 86
        if ($metadata->inline) {
134 9
            if (\is_array($v) || ($v instanceof \ArrayObject)) {
135
                // concatenate the two array-like structures
136
                // is there anything faster?
137 9
                foreach ($v as $key => $value) {
138 9
                    $this->data[$key] = $value;
139
                }
140
            }
141
        } else {
142 79
            $this->data[$metadata->serializedName] = $v;
143
        }
144 86
    }
145
146
    /**
147
     * @deprecated Will be removed in 3.0
148
     *
149
     * Checks if some data key exists.
150
     * @param string $key
151
     * @return boolean
152 1
     */
153
    public function hasData(string $key): bool
154 1
    {
155
        return isset($this->data[$key]);
156
    }
157
158
    /**
159
     * @deprecated Use visitProperty(new StaticPropertyMetadata(null, 'name', 'value'), null) instead
160
     *
161
     * Allows you to replace existing data on the current object element.
162
     *
163
     * @param string $key
164 2
     * @param mixed $value This value must either be a regular scalar, or an array.
165
     *                                                       It must not contain any objects anymore.
166 2
     */
167 2
    public function setData(string $key, $value): void
168
    {
169 147
        $this->data[$key] = $value;
170
    }
171 147
172
    public function getResult($data)
173 147
    {
174 147
        $result = @json_encode($data, $this->options);
175 145
176
        switch (json_last_error()) {
177 2
            case JSON_ERROR_NONE:
178 2
                return $result;
179
180
            case JSON_ERROR_UTF8:
181
                throw new RuntimeException('Your data could not be encoded because it contains invalid UTF8 characters.');
182
183
            default:
184
                throw new RuntimeException(sprintf('An error occurred while encoding your data (error code %d).', json_last_error()));
185
        }
186
    }
187
}
188