Completed
Push — master ( 6bc3b4...34ca55 )
by Ralf
15s queued 11s
created

AbstractJsonSerializer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 46
rs 10
c 0
b 0
f 0
wmc 6
1
<?php
2
3
namespace Elasticsearch\Serializers;
4
5
use Elasticsearch\Common\Exceptions\Serializer\JsonSerializationError;
6
use Elasticsearch\Common\Exceptions\Serializer\JsonDeserializationError;
7
8
/**
9
 * An abstract base class for serializers that go to/from JSON.
10
 *
11
 * @author   Christopher Davis <[email protected]>
12
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
13
 * @link     http://elasticsearch.org
14
 */
15
abstract class AbstractJsonSerializer implements SerializerInterface
16
{
17
    /**
18
     * Encode a php object or array to a JSON string
19
     *
20
     * @param   object|array $value
21
     * @throws  JsonSerializationError if something goes wrong during encoding
22
     * @return  string
23
     */
24
    protected static function jsonEncode($value)
25
    {
26
        $result = json_encode($value);
27
28
        if (static::hasJsonError()) {
29
            throw new JsonSerializationError(json_last_error(), $value, $result);
30
        }
31
32
        return '[]' === $result ? '{}' : $result;
33
    }
34
35
    /**
36
     * Decode a JSON string to a PHP array.
37
     *
38
     * @param   string $json
39
     * @throws  JsonDeserializationError if something goes wrong during decoding
40
     * @return  array
41
     */
42
    protected static function jsonDecode($json)
43
    {
44
        $result = json_decode($json, true);
45
46
        if (static::hasJsonError()) {
47
            throw new JsonDeserializationError(json_last_error(), $json, $result);
48
        }
49
50
        return $result;
51
    }
52
53
    /**
54
     * Check to see if the last `json_{encode,decode}` call produced an error.
55
     *
56
     * @return  boolean
57
     */
58
    protected static function hasJsonError()
59
    {
60
        return json_last_error() !== JSON_ERROR_NONE;
61
    }
62
}
63