Passed
Push — main ( e16d46...16e3d2 )
by Damien
07:21
created

BlockNode::load()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 26
c 1
b 0
f 0
rs 9.5222
cc 5
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DH\Adf\Node;
6
7
use InvalidArgumentException;
8
9
abstract class BlockNode extends Node
10
{
11
    protected array $allowedContentTypes = [];
12
    protected array $content = [];
13
14
    public function jsonSerialize(): array
15
    {
16
        $result = parent::jsonSerialize();
17
        $result['content'] = $this->content;
18
19
        return $result;
20
    }
21
22
    public static function load(array $data, ?self $parent = null): self
23
    {
24
        self::checkNodeData(static::class, $data);
25
26
        $class = Node::NODE_MAPPING[$data['type']];
27
        $node = new $class($parent);
28
        \assert($node instanceof self);
29
30
        // set attributes if defined
31
        if (\array_key_exists('attrs', $data)) {
32
            foreach ($data['attrs'] as $key => $value) {
33
                $node->{$key} = $value;
34
            }
35
        }
36
37
        // set content if defined
38
        if (\array_key_exists('content', $data)) {
39
            foreach ($data['content'] as $nodeData) {
40
                $class = Node::NODE_MAPPING[$nodeData['type']];
41
                $child = $class::load($nodeData, $node);
42
43
                $node->append($child);
44
            }
45
        }
46
47
        return $node;
48
    }
49
50
    protected function append(Node $node): void
51
    {
52
        foreach ($this->allowedContentTypes as $type) {
53
            if ($node instanceof $type) {
54
                $this->content[] = $node;
55
56
                return;
57
            }
58
        }
59
60
        throw new InvalidArgumentException(sprintf('Invalid content type "%s" for block node "%s".', $node->type, $this->type));
61
    }
62
}
63