Passed
Push — master ( 95373b...dd07b4 )
by Nate
43s
created

JsonWriter::assertionFailed()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
declare(strict_types=1);
7
8
9
namespace Tebru\Gson\Internal;
10
11
use LogicException;
12
use Tebru\Gson\JsonWritable;
13
14
/**
15
 * Class JsonWriter
16
 *
17
 * @author Nate Brunette <[email protected]>
18
 */
19
abstract class JsonWriter implements JsonWritable
20
{
21
    use JsonPath;
22
23
    /**
24
     * True if we should serialize nulls
25
     *
26
     * @var bool
27
     */
28
    protected $serializeNull = false;
29
30
    /**
31
     * Stack of values to be written
32
     *
33
     * @var array
34
     */
35
    protected $stack = [];
36
37
    /**
38
     * Size of the stack array
39
     *
40
     * @var int
41
     */
42
    protected $stackSize = 0;
43
44
    /**
45
     * A cache of the parsing state corresponding to the stack
46
     *
47
     * @var int[]
48
     */
49
    protected $stackStates = [];
50
51
    /**
52
     * When serializing an object, store the name that should be serialized
53
     *
54
     * @var
55
     */
56
    protected $pendingName;
57
58
    /**
59
     * The final result that will be json encoded
60
     *
61
     * @var mixed
62
     */
63
    protected $result;
64
65
    /**
66
     * Writes a property name
67
     *
68
     * @param string $name
69
     * @return JsonWritable
70
     * @throws LogicException
71
     */
72 36
    public function name(string $name): JsonWritable
73
    {
74 36
        if ($this->stackStates[$this->stackSize - 1] !== self::STATE_OBJECT_NAME) {
75 2
            $this->assertionFailed('Cannot call name() at this point.  Either name() has already been called or object serialization has not been started');
76
        }
77
78 36
        $this->pendingName = $name;
79 36
        $this->stackStates[$this->stackSize - 1] = self::STATE_OBJECT_VALUE;
80 36
        $this->pathNames[$this->pathIndex] = $name;
81
82 36
        return $this;
83
    }
84
85
    /**
86
     * Sets whether nulls are serialized
87
     *
88
     * @param bool $serializeNull
89
     * @return void
90
     */
91 12
    public function setSerializeNull(bool $serializeNull): void
92
    {
93 12
        $this->serializeNull = $serializeNull;
94 12
    }
95
96
    /**
97
     * Thrown in there's a logic error during serialization
98
     *
99
     * @param string $message
100
     * @throws \LogicException
101
     */
102 30
    protected function assertionFailed(string $message): void
103
    {
104 30
        throw new LogicException($message.\sprintf(' at "%s"', $this->getPath()));
105
    }
106
}
107