Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
77.78% covered (warning)
77.78%
7 / 9
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
JsonSerializer
77.78% covered (warning)
77.78%
7 / 9
33.33% covered (danger)
33.33%
1 / 3
5.27
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 saveImpl
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 loadImpl
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
1<?php
2
3declare(strict_types=1);
4
5namespace PeServer\Core\Serialization;
6
7use JsonException;
8use Exception;
9use PeServer\Core\Binary;
10use PeServer\Core\Serialization\SerializerBase;
11use PeServer\Core\Throws\JsonDecodeException;
12use PeServer\Core\Throws\JsonEncodeException;
13use PeServer\Core\Throws\ParseException;
14use PeServer\Core\Throws\Throws;
15
16/**
17 * JSONシリアライザー。
18 */
19class JsonSerializer extends SerializerBase
20{
21    #region define
22
23    public const SAVE_NONE = 0;
24    public const SAVE_PRETTY = JSON_PRETTY_PRINT;
25    public const SAVE_UNESCAPED_SLASHES = JSON_UNESCAPED_SLASHES;
26    public const SAVE_UNESCAPED_UNICODE = JSON_UNESCAPED_UNICODE;
27    public const SAVE_DEFAULT = self::SAVE_PRETTY | self::SAVE_UNESCAPED_UNICODE;
28
29    public const LOAD_NONE = 0;
30    public const LOAD_DEFAULT = self::LOAD_NONE;
31
32    public const DEFAULT_DEPTH = 512;
33
34    #endregion
35
36    /**
37     * 生成。
38     *
39     * @param int $saveOption
40     * @phpstan-param self::SAVE_* $saveOption
41     * @param int $loadOption
42     * @phpstan-param self::LOAD_* $loadOption
43     * @param int $depth
44     * @phpstan-param positive-int $depth
45     */
46    public function __construct(
47        protected int $saveOption = self::SAVE_DEFAULT,
48        protected int $loadOption = self::LOAD_DEFAULT,
49        protected int $depth = self::DEFAULT_DEPTH
50    ) {
51    }
52
53    #region SerializerBase
54
55    protected function saveImpl(array|object $value): Binary
56    {
57        $json = json_encode($value, $this->saveOption | JSON_THROW_ON_ERROR, $this->depth);
58        if ($json == false) {
59            throw new Exception(json_last_error_msg(), json_last_error());
60        }
61
62        return new Binary($json);
63    }
64
65    //@phpstan-ignore return.unusedType (objectは返らないけどインターフェイス的にこうなる)
66    protected function loadImpl(Binary $value): array|object
67    {
68        $value = json_decode($value->toString(), true, $this->depth, $this->loadOption | JSON_THROW_ON_ERROR);
69        if ($value === null) {
70            throw new Exception(json_last_error_msg(), json_last_error());
71        }
72
73        return $value;
74    }
75
76    #endregion
77}