BlockNode   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 57
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 26 5
A jsonSerialize() 0 6 1
A append() 0 11 3
A getContent() 0 3 1
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
    protected function append(Node $node): void
56
    {
57
        foreach ($this->allowedContentTypes as $type) {
58
            if ($node instanceof $type) {
59
                $this->content[] = $node;
60
61
                return;
62
            }
63
        }
64
65
        throw new InvalidArgumentException(sprintf('Invalid content type "%s" for block node "%s".', $node->type, $this->type));
66
    }
67
}
68