Passed
Push — main ( 7f60ea...60225c )
by Thierry
08:29
created

Scope::build()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 7
c 3
b 0
f 0
dl 0
loc 15
rs 10
cc 3
nc 4
nop 1
1
<?php
2
3
namespace Lagdo\UiBuilder\Builder\Html;
4
5
use AvpLab\Element\Element as Block;
6
7
use function is_a;
8
use function implode;
9
10
class Scope
11
{
12
    /**
13
     * @var array<Element>
14
     */
15
    protected $children = [];
16
17
    /**
18
     * The constructor
19
     *
20
     * @param Element $parent
21
     * @param array<Block> $blocks
22
     */
23
    public function __construct(protected Element $parent, protected array $blocks = [])
24
    {}
25
26
    /**
27
     * Create the corresponding elements
28
     *
29
     * @param mixed $element
30
     *
31
     * @return void
32
     */
33
    private function expand(mixed $element): void
34
    {
35
        if (is_a($element, Element::class)) {
36
            $this->children[] = $element;
37
            return;
38
        }
39
        if (!is_a($element, ElementExpr::class)) {
40
            return;
41
        }
42
43
        // Recursively expand the children of the ElementExpr element.
44
        foreach ($element->children as $childElement) {
45
            $this->expand($childElement);
46
        }
47
    }
48
49
    /**
50
     * @param Element $element
51
     * @param Scope $scope
52
     *
53
     * @return ElementBlock
54
     */
55
    private function createBlock(Element $element, Scope $scope): ElementBlock
56
    {
57
        $block = new ElementBlock($element, $scope->blocks);
58
        foreach ($element->wrappers as $wrapper) {
59
            $block = new ElementBlock($wrapper, [$block]);
60
        }
61
        return $block;
62
    }
63
64
    /**
65
     * @param array $arguments The arguments passed to the element
66
     *
67
     * @return void
68
     */
69
    public function build(array $arguments): void
70
    {
71
        foreach ($arguments as $argument) {
72
            $this->expand($argument);
73
        }
74
75
        foreach ($this->children as $element) {
76
            $element->onBuild($this->parent);
77
78
            // Recursively build the child scope.
79
            $scope = new Scope($element, $element->blocks);
80
            $scope->build($element->children);
81
82
            // Generate the corresponding tag.
83
            $this->blocks[] = $this->createBlock($element, $scope);
84
        }
85
    }
86
87
    /**
88
     * @return string
89
     */
90
    public function html(): string
91
    {
92
        // Merge all the generated tags.
93
        return implode('', $this->blocks);
94
    }
95
}
96