Children::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace BestServedCold\HTMLBuilder\Html\Node;
4
5
use BestServedCold\HTMLBuilder\Html\Node, Closure;
6
7
/**
8
 * Class Children
9
 *
10
 * @package BestServedCold\HTMLBuilder\Html\Node
11
 */
12
class Children
13
{
14
    /**
15
     * @var array $allowedTypes
16
     */
17
    private $allowedTypes = [
18
        Node::class,
19
        Closure::class,
20
        'array'
21
    ];
22
23
    /**
24
     * @var Node $node
25
     */
26
    private $node;
27
28
    /**
29
     * Children constructor.
30
     *
31
     * @param Node  $node
32
     */
33 10
    public function __construct(Node $node)
34
    {
35 10
        $this->node     = $node;
36 10
    }
37
38
    /**
39
     * @param  Node  $node
40
     * @param  array $children
41
     * @return mixed
42
     */
43 10
    public static function run(Node $node, array $children)
44
    {
45 10
        return (new static($node))->loop($children);
46
    }
47
48
    /**
49
     * @param array $children
50
     */
51 10
    private function loop(array $children)
52
    {
53
        /** @var Node|array|Closure $child */
54 10
        foreach ($children as $child) {
55 10
            $type = $this->realType($child);
56 10
            $this->checkType($type);
57 9
            $this->child($type === 'Closure' ? call_user_func($child) : $child);
58 9
        }
59 9
    }
60
61
    /**
62
     * @param  Node|array $node
63
     * @return $this
64
     */
65 9
    private function child($node)
66
    {
67 9
        is_array($node) ? $this->loop($node) : $this->node->child($node);
68 9
        return $this;
69
    }
70
71
    /**
72
     * @param  mixed  $type
73
     * @return string
74
     */
75 10
    private function realType($type)
76
    {
77 10
        $phpType = gettype($type);
78 10
        return $phpType === 'object' ? get_class($type) : $phpType;
79
    }
80
81
    /**
82
     * @param $type
83
     * @throws \Exception
84
     */
85 10
    private function checkType($type)
86
    {
87 10
        if (! in_array($type, $this->allowedTypes)) {
88 1
            throw new \Exception('Type [' . $type . '] not allowed.');
89
        }
90 9
    }
91
}
92