JsonSerializer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 6
eloc 23
c 3
b 0
f 1
dl 0
loc 61
ccs 18
cts 18
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A type() 0 3 1
A unserialize() 0 11 2
A __construct() 0 4 1
A serialize() 0 7 2
1
<?php
2
3
/*
4
 * This file is part of the Koded package.
5
 *
6
 * (c) Mihail Binev <[email protected]>
7
 *
8
 * Please view the LICENSE distributed with this source code
9
 * for the full copyright and license information.
10
 */
11
12
namespace Koded\Stdlib\Serializer;
13
14
use JsonException;
15
use Koded\Stdlib\Serializer;
16
use function Koded\Stdlib\error_log;
17
18
class JsonSerializer implements Serializer
19
{
20
    public const OPTIONS = JSON_PRESERVE_ZERO_FRACTION
21
    | JSON_UNESCAPED_SLASHES
22
    | JSON_UNESCAPED_UNICODE
23
    | JSON_THROW_ON_ERROR;
24
25
    /**
26
     * @var int JSON encode options. Defaults to (4195648):
27
     *          - JSON_PRESERVE_ZERO_FRACTION
28
     *          - JSON_UNESCAPED_SLASHES
29
     *          - JSON_UNESCAPED_UNICODE
30
     *          - JSON_THROW_ON_ERROR
31
     */
32
    private int $options = self::OPTIONS;
33
34
    private bool $associative;
35
36
    /**
37
     * JsonSerializer constructor.
38
     *
39
     * @param int $options [optional] JSON encode options.
40
     *                          - to ADD more JSON options use OR "|" bitmask operator
41
     *                          - to EXCLUDE multiple default options use XOR "^"
42
     * @param bool $associative [optional] When TRUE, returned objects will be
43
     *                          converted into associative arrays
44
     */
45 35
    public function __construct(int $options = 0, bool $associative = false)
46
    {
47 35
        $this->options ^= $options;
48 35
        $this->associative = $associative;
49
    }
50
51 21
    public function serialize(mixed $value): ?string
52
    {
53
        try {
54 21
            return json_encode($value, $this->options);
55 1
        } catch (JsonException $e) {
56 1
            error_log(__METHOD__, $e->getMessage(), $value);
57 1
            return '';
58
        }
59
60
    }
61
62 10
    public function unserialize(string $value): mixed
63
    {
64
        try {
65 10
            return json_decode($value, $this->associative, 512,
66 10
                JSON_OBJECT_AS_ARRAY
67 10
                | JSON_BIGINT_AS_STRING
68 10
                | JSON_THROW_ON_ERROR);
69
70 2
        } catch (JsonException $e) {
71 2
            error_log(__METHOD__, $e->getMessage(), $value);
72 2
            return '';
73
        }
74
    }
75
76 2
    public function type(): string
77
    {
78 2
        return Serializer::JSON;
79
    }
80
}
81