Completed
Push — master ( e6d18b...825aa7 )
by Chris
03:21
created

VectorNode::updateLastChildIfChanged()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 2
crap 2
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\Jom;
4
5
use DaveRandom\Jom\Exceptions\InvalidKeyException;
6
use DaveRandom\Jom\Exceptions\InvalidReferenceNodeException;
7
use DaveRandom\Jom\Exceptions\InvalidSubjectNodeException;
8
use DaveRandom\Jom\Exceptions\WriteOperationForbiddenException;
9
10
abstract class VectorNode extends Node implements \Countable, \IteratorAggregate, \ArrayAccess
11
{
12
    /** @var Node|null */
13
    protected $firstChild;
14
15
    /** @var Node|null */
16
    protected $lastChild;
17
18
    /** @var Node[] */
19
    protected $children = [];
20
21
    /** @var int */
22
    protected $activeIteratorCount = 0;
23
24
    /**
25
     * @throws WriteOperationForbiddenException
26
     */
27 85
    private function checkWritable(): void
28
    {
29 85
        if ($this->activeIteratorCount !== 0) {
30 5
            throw new WriteOperationForbiddenException('Cannot modify a vector with an active iterator');
31
        }
32
    }
33
34
    /**
35
     * @throws InvalidSubjectNodeException
36
     */
37 76
    private function checkSubjectNodeIsOrphan(Node $node): void
38
    {
39 76
        if ($node->parent !== null) {
40 14
            throw new InvalidSubjectNodeException('Node already present in the document');
41
        }
42
    }
43
44
    /**
45
     * @throws InvalidSubjectNodeException
46
     */
47 85
    private function checkSubjectNodeHasSameOwner(Node $node): void
48
    {
49 85
        if ($node->ownerDocument !== $this->ownerDocument) {
50 15
            throw new InvalidSubjectNodeException('Node belongs to a different document');
51
        }
52
53
    }
54
55
    /**
56
     * @throws InvalidSubjectNodeException
57
     */
58 18
    private function checkSubjectNodeIsChild(Node $node): void
59
    {
60 18
        if ($node->parent !== $this) {
61
            throw new InvalidSubjectNodeException('Node not present in children of this node');
62
        }
63
64
    }
65
66
    /**
67
     * @throws InvalidReferenceNodeException
68
     */
69 22
    private function checkReferenceNodeIsChild(Node $node): void
70
    {
71 22
        if ($node->parent !== $this) {
72 2
            throw new InvalidReferenceNodeException('Reference node not present in children of this node');
73
        }
74
75
    }
76
77 74
    private function updateFirstChildIfChanged(?Node $newNode, ?Node $oldNode): void
78
    {
79 74
        if ($this->firstChild === $oldNode) {
80 74
            $this->firstChild = $newNode;
81
        }
82
    }
83
84 25
    private function updateLastChildIfChanged(?Node $newNode, ?Node $oldNode): void
85
    {
86 25
        if ($this->lastChild === $oldNode) {
87 22
            $this->lastChild = $newNode;
88
        }
89
    }
90
91 25
    private function setNodePreviousSibling(?Node $node, ?Node $newSiblingNode): void
92
    {
93 25
        if ($node !== null) {
94 12
            $node->previousSibling = $newSiblingNode;
95
        }
96
    }
97
98 74
    private function setNodeNextSibling(?Node $node, ?Node $newSiblingNode): void
99
    {
100 74
        if ($node !== null) {
101 36
            $node->nextSibling = $newSiblingNode;
102
        }
103
    }
104
105
    /**
106
     * @throws InvalidKeyException
107
     */
108 11
    protected function resolveNode($nodeOrKey): Node
109
    {
110 11
        if ($nodeOrKey instanceof Node) {
111 11
            return $nodeOrKey;
112
        }
113
114
        if (isset($this->children[$nodeOrKey])) {
115
            return $this->children[$nodeOrKey];
116
        }
117
118
        throw new InvalidKeyException("{$nodeOrKey} does not reference a valid child node");
119
    }
120
121
    /**
122
     * @throws WriteOperationForbiddenException
123
     * @throws InvalidSubjectNodeException
124
     */
125 82
    protected function appendNode(Node $node, $key): Node
126
    {
127
        // Prevent modifying a collection with an active iterator
128 82
        $this->checkWritable();
129
130
        // Validate arguments
131 82
        $this->checkSubjectNodeHasSameOwner($node);
132 74
        $this->checkSubjectNodeIsOrphan($node);
133
134
        // Update first/last child pointers
135 74
        $this->updateFirstChildIfChanged($node, null);
136 74
        $previousSibling = $this->lastChild;
137 74
        $this->lastChild = $node;
138
139
        // Update next sibling pointer of old $lastChild (no next sibling node to update)
140 74
        $this->setNodeNextSibling($previousSibling, $node);
141
142
        // Add the child to the key map
143 74
        $this->children[$key] = $node;
144
145
        // Set references on new child
146 74
        $node->setReferences($this, $key, $previousSibling, null);
147
148 74
        return $node;
149
    }
150
151
    /**
152
     * @throws WriteOperationForbiddenException
153
     * @throws InvalidSubjectNodeException
154
     * @throws InvalidReferenceNodeException
155
     */
156 33
    protected function insertNode(Node $node, $key, Node $before = null): Node
157
    {
158
        // A null $before reference means push the node on to the end of the list
159 33
        if ($before === null) {
160 13
            return $this->appendNode($node, $key);
161
        }
162
163
        // Prevent modifying a collection with an active iterator
164 29
        $this->checkWritable();
165
166
        // Validate arguments
167 26
        $this->checkSubjectNodeHasSameOwner($node);
168 20
        $this->checkSubjectNodeIsOrphan($node);
169 14
        $this->checkReferenceNodeIsChild($before);
170
171
        // Update first child pointer (last child pointer is not affected)
172 13
        $this->updateFirstChildIfChanged($node, $before);
173
174
        // Update next sibling pointer of previous sibling of $before
175 13
        $this->setNodeNextSibling($before->previousSibling, $node);
176
177
        // Replace the child in the key map
178 13
        $this->children[$key] = $node;
179
180
        // Set references on new child
181 13
        $node->setReferences($this, $key, $before->previousSibling, $before);
182
183
        // Update references on ref child
184 13
        $before->setReferences($before->parent, $before->key, $node, $before->nextSibling);
185
186 13
        return $node;
187
    }
188
189
    /**
190
     * @throws WriteOperationForbiddenException
191
     * @throws InvalidSubjectNodeException
192
     * @throws InvalidReferenceNodeException
193
     */
194 11
    protected function replaceNode(Node $newNode, Node $oldNode): Node
195
    {
196
        // Prevent modifying a collection with an active iterator
197 11
        $this->checkWritable();
198
199
        // Validate arguments
200 11
        $this->checkSubjectNodeHasSameOwner($newNode);
201 11
        $this->checkSubjectNodeIsOrphan($newNode);
202 8
        $this->checkReferenceNodeIsChild($oldNode);
203
204
        // Update first/last child pointers
205 7
        $this->updateFirstChildIfChanged($newNode, $oldNode);
206 7
        $this->updateLastChildIfChanged($newNode, $oldNode);
207
208
        // Update sibling pointers of sibling nodes
209 7
        $this->setNodeNextSibling($oldNode->previousSibling, $newNode);
210 7
        $this->setNodePreviousSibling($oldNode->nextSibling, $newNode);
211
212
        // Replace the node in the key map
213 7
        $this->children[$oldNode->key] = $newNode;
214
215
        // Copy references from old node to new node
216 7
        $newNode->setReferences($oldNode->parent, $oldNode->key, $oldNode->previousSibling, $oldNode->nextSibling);
217
218
        // Clear references from old node
219 7
        $oldNode->setReferences(null, null, null, null);
220
221 7
        return $oldNode;
222
    }
223
224
    /**
225
     * @throws WriteOperationForbiddenException
226
     * @throws InvalidSubjectNodeException
227
     */
228 18
    protected function removeNode(Node $node): Node
229
    {
230
        // Prevent modifying a collection with an active iterator
231 18
        $this->checkWritable();
232
233
        // Validate arguments
234 18
        $this->checkSubjectNodeIsChild($node);
235
236
        // Update first/last child pointers
237 18
        $this->updateFirstChildIfChanged($node->nextSibling, $node);
238 18
        $this->updateLastChildIfChanged($node->previousSibling, $node);
239
240
        // Update sibling pointers of sibling nodes
241 18
        $this->setNodeNextSibling($node->previousSibling, $node->nextSibling);
242 18
        $this->setNodePreviousSibling($node->nextSibling, $node->previousSibling);
243
244
        // Remove the node from the key map
245 18
        unset($this->children[$node->key]);
246
247
        // Clear references from node
248 18
        $node->setReferences(null, null, null, null);
249
250 18
        return $node;
251
    }
252
253
    public function hasChildren(): bool
254
    {
255
        return !empty($this->children);
256
    }
257
258 12
    public function getFirstChild(): ?Node
259
    {
260 12
        return $this->firstChild;
261
    }
262
263 10
    public function getLastChild(): ?Node
264
    {
265 10
        return $this->lastChild;
266
    }
267
268
    final public function clear(): void
269
    {
270
        try {
271
            while ($this->lastChild !== null) {
272
                $this->removeNode($this->lastChild);
273
            }
274
        //@codeCoverageIgnoreStart
275
        } catch (\Exception $e) {
276
            throw new \Error('Unexpected ' . \get_class($e) . ": {$e->getMessage()}", 0, $e);
277
        }
278
        //@codeCoverageIgnoreEnd
279
    }
280
281
    final public function getIterator(): NodeListIterator
282
    {
283 5
        return new NodeListIterator($this->firstChild, function($state) {
284 5
            $this->activeIteratorCount += $state;
285 5
            \assert($this->activeIteratorCount >= 0, new \Error('Vector node active iterator count is negative'));
286 5
        });
287
    }
288
289
    final public function count(): int
290
    {
291
        return \count($this->children);
292
    }
293
294
    final public function jsonSerialize(): array
295
    {
296
        return \iterator_to_array($this->getIterator());
297
    }
298
299
    public function offsetExists($key): bool
300
    {
301
        return isset($this->children[$key]);
302
    }
303
304
    /**
305
     * @throws WriteOperationForbiddenException
306
     * @throws InvalidSubjectNodeException
307
     */
308
    public function offsetUnset($key): void
309
    {
310
        if (isset($this->children[$key])) {
311
            $this->removeNode($this->children[$key]);
312
        }
313
    }
314
315
    abstract public function toArray(): array;
316
    abstract public function offsetGet($index): Node;
317
    abstract public function offsetSet($index, $value): void;
318
}
319