Completed
Pull Request — master (#944)
by Asmir
02:57
created

JsonSerializationVisitor::endVisitingObject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 3
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
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 178
    public function __construct(
40
        int $options = JSON_PRESERVE_ZERO_FRACTION)
41
    {
42 178
        $this->dataStack = new \SplStack;
43 178
        $this->options = $options;
44 178
    }
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 30
    public function visitInteger(int $data, array $type)
62
    {
63 30
        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 82
    public function visitArray(array $data, array $type)
77
    {
78 82
        $this->dataStack->push($data);
79
80 82
        $rs = isset($type['params'][1]) ? new \ArrayObject() : [];
81
82 82
        $isList = isset($type['params'][0]) && !isset($type['params'][1]);
83
84 82
        $elType = $this->getElementType($type);
85 82
        foreach ($data as $k => $v) {
86
87
            try {
88 74
                $v = $this->navigator->accept($v, $elType);
89 6
            } catch (NotAcceptableException $e) {
90 6
                continue;
91
            }
92
93 71
            if ($isList) {
94 19
                $rs[] = $v;
95
            } else {
96 71
                $rs[$k] = $v;
97
            }
98
        }
99
100 82
        $this->dataStack->pop();
101 82
        return $rs;
102
    }
103
104 95
    public function startVisitingObject(ClassMetadata $metadata, object $data, array $type): void
105
    {
106 95
        $this->dataStack->push($this->data);
107 95
        $this->data = new \ArrayObject();
108 95
    }
109
110 94
    public function endVisitingObject(ClassMetadata $metadata, object $data, array $type)
111
    {
112 94
        $rs = $this->data;
113 94
        $this->data = $this->dataStack->pop();
114
115 94
        if ($metadata->isList) {
116 3
            return array_values((array)$rs);
117
        }
118
119 91
        return $rs;
120
    }
121
122 88
    public function visitProperty(PropertyMetadata $metadata, $v): void
123
    {
124
        try {
125 88
            $v = $this->navigator->accept($v, $metadata->type);
126 4
        } catch (NotAcceptableException $e) {
127 4
            return;
128
        }
129
130 88
        if (true === $metadata->skipWhenEmpty && ($v instanceof \ArrayObject || \is_array($v)) && 0 === count($v)) {
131 2
            return;
132
        }
133
134 87
        if ($metadata->inline) {
135 10
            if (\is_array($v) || ($v instanceof \ArrayObject)) {
136
                // concatenate the two array-like structures
137
                // is there anything faster?
138 10
                foreach ($v as $key => $value) {
139 10
                    $this->data[$key] = $value;
140
                }
141
            }
142
        } else {
143 79
            $this->data[$metadata->serializedName] = $v;
144
        }
145 87
    }
146
147
    /**
148
     * Checks if some data key exists.
149
     *
150
     * @param string $key
151
     * @return boolean
152
     */
153 1
    public function hasData(string $key): bool
154
    {
155 1
        return isset($this->data[$key]);
156
    }
157
158
    /**
159
     * Allows you to replace existing data on the current object/root element.
160
     *
161
     * @param string $key
162
     * @param mixed $value This value must either be a regular scalar, or an array.
163
     *                                                       It must not contain any objects anymore.
164
     */
165 2
    public function setData(string $key, $value): void
166
    {
167 2
        $this->data[$key] = $value;
168 2
    }
169
170 148
    public function getResult($data)
171
    {
172 148
        $result = @json_encode($data, $this->options);
173
174 148
        switch (json_last_error()) {
175 148
            case JSON_ERROR_NONE:
176 146
                return $result;
177
178 2
            case JSON_ERROR_UTF8:
179 2
                throw new RuntimeException('Your data could not be encoded because it contains invalid UTF8 characters.');
180
181
            default:
182
                throw new RuntimeException(sprintf('An error occurred while encoding your data (error code %d).', json_last_error()));
183
        }
184
    }
185
}
186