Completed
Push — master ( 6b8c98...e0ddec )
by Daniel
02:56
created

NativeJsonSerializer::deserialize()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 8.1427

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 30
ccs 10
cts 14
cp 0.7143
rs 6.7273
cc 7
eloc 15
nc 5
nop 2
crap 8.1427
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license.
17
 */
18
namespace Elastification\Client\Serializer;
19
20
use Elastification\Client\Serializer\Exception\DeserializationFailureException;
21
use Elastification\Client\Serializer\Gateway\NativeArrayGateway;
22
use Elastification\Client\Serializer\Gateway\NativeObjectGateway;
23
24
/**
25
 * Simple Native JSON Serializer.
26
 *
27
 * Serializes the response using the native json_encode/json_decode commands. the params allow you to control
28
 * the type of result, either a stdClass or an array/hash map.
29
 *
30
 * @package Elastification\Client\Serializer
31
 * @author  Daniel Wendlandt
32
 */
33
class NativeJsonSerializer implements SerializerInterface
34
{
35
36
    /**
37
     * @inheritdoc
38
     */
39 5
    public function serialize($data, array $params = array())
40
    {
41 5
        $forceObject = $this->forceObject($params);
42
43 5
        return json_encode($data, $forceObject);
44
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49 5
    public function deserialize($data, array $params = array())
50
    {
51 5
        $assoc = $this->useAssoc($params);
52 5
        $decodedJson = json_decode($data, $assoc);
53
54 5
        if ($decodedJson !== null) {
55 3
            return $this->createGateway($assoc, $decodedJson);
56
        }
57
58
        // json_last_error_msg is only present in 5.5 and higher.
59 2
        if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
60 2
            $jsonLastError = json_last_error();
61
62
            if (
63 2
                JSON_ERROR_NONE === $jsonLastError
64 2
                && ($data === '' || '{}' == $data)
65
            ) {
66
                return $this->createGateway($assoc, array());
67
            }
68
69 2
            throw new DeserializationFailureException(json_last_error_msg(), $jsonLastError);
70
        }
71
72
        if ($data === '') {
73
            return $this->createGateway($assoc, array());
74
        }
75
76
        // Fall through for versions below 5.5
77
        throw new DeserializationFailureException('JSON syntax error in: ' . $data);
78
    }
79
80
    /**
81
     * Decides whether to use assoc or stdClass.
82
     *
83
     * @param array $params The array of params.
84
     *
85
     * @return boolean
86
     * @author Mario Mueller
87
     */
88 5
    private function useAssoc($params)
89
    {
90 5
        $assoc = true;
91 5
        if (isset($params['assoc']) && is_bool($params['assoc'])) {
92 3
            $assoc = $params['assoc'];
93
        }
94
95 5
        return $assoc;
96
    }
97
98
    /**
99
     * Decides whether to force objects.
100
     *
101
     * @param array $params The array of params.
102
     *
103
     * @return integer
104
     * @author Patrick Pokatilo <[email protected]>
105
     */
106 5
    private function forceObject($params)
107
    {
108 5
        $forceObject = false;
109 5
        if (isset($params['force_object']) && is_bool($params['force_object']) && true === $params['force_object']) {
110 1
            $forceObject = JSON_FORCE_OBJECT;
111
        }
112
113 5
        return $forceObject;
114
    }
115
116
    /**
117
     * Creates the correct gateway based on assoc being true or false.
118
     *
119
     * The information if we need assoc could also be determined by looking
120
     * at the type of $decodedJson, but we thing a boolean is faster and the
121
     * decision has already been made before.
122
     *
123
     * @author Mario Mueller
124
     *
125
     * @param boolean         $assoc Should we use assoc?
126
     * @param array|\stdClass $decodedJson
127
     *
128
     * @return \Elastification\Client\Serializer\Gateway\GatewayInterface
129
     */
130 3
    private function createGateway($assoc, $decodedJson)
131
    {
132 3
        if ($assoc === true) {
133 2
            $instance = new NativeArrayGateway($decodedJson);
0 ignored issues
show
Bug introduced by
It seems like $decodedJson defined by parameter $decodedJson on line 130 can also be of type object<stdClass>; however, Elastification\Client\Se...yGateway::__construct() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
134
        } else {
135 1
            $instance = new NativeObjectGateway($decodedJson);
0 ignored issues
show
Bug introduced by
It seems like $decodedJson defined by parameter $decodedJson on line 130 can also be of type array; however, Elastification\Client\Se...tGateway::__construct() does only seem to accept object, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
136
        }
137
138 3
        return $instance;
139
    }
140
}
141