Passed
Pull Request — main (#16)
by
unknown
01:59
created

BlockNode::isAppendAllowed()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
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
    public function getContent(): array
51
    {
52
        return $this->content;
53
    }
54
55
    public function append(Node ...$nodes): BlockNode
56
    {
57
        foreach ($nodes as $node) {
58
            if ($this->isAppendAllowed($node)) {
59
                $this->content[] = $node;
60
            } else {
61
                throw new InvalidArgumentException(
62
                    sprintf('Invalid content type "%s" for block node "%s".', $node->getType(), $this->getType())
63
                );
64
            }
65
        }
66
67
        return $this;
68
    }
69
70
    protected function isAppendAllowed(Node $node): bool
71
    {
72
        foreach ($this->allowedContentTypes as $allowedContentType) {
73
            if ($node instanceof $allowedContentType) {
74
                return true;
75
            }
76
        }
77
78
        return false;
79
    }
80
}
81