Completed
Pull Request — master (#2)
by Adam
01:53
created

Children   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 85
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 1
dl 0
loc 85
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A run() 0 4 1
A loop() 0 9 3
A child() 0 5 2
A realType() 0 5 2
A checkType() 0 6 2
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
     * @var array $children
30
     */
31
    private $children;
0 ignored issues
show
Unused Code introduced by
The property $children is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
32
33
    /**
34
     * Children constructor.
35
     *
36
     * @param Node  $node
37
     */
38
    public function __construct(Node $node)
39
    {
40
        $this->node     = $node;
41
    }
42
43
    /**
44
     * @param  Node  $node
45
     * @param  array $children
46
     * @return mixed
47
     */
48
    public static function run(Node $node, array $children)
49
    {
50
        return (new static($node))->loop($children);
51
    }
52
53
    /**
54
     * @param array $children
55
     */
56
    private function loop(array $children)
57
    {
58
        /** @var Node|array|Closure $child */
59
        foreach ($children as $child) {
60
            $type = $this->realType($child);
61
            $this->checkType($type);
62
            $this->child($type === 'Closure' ? call_user_func($child) : $child);
63
        }
64
    }
65
66
    /**
67
     * @param  Node|array $node
68
     * @return $this
69
     */
70
    private function child($node)
71
    {
72
        is_array($node) ? $this->loop($node) : $this->node->child($node);
73
        return $this;
74
    }
75
76
    /**
77
     * @param  mixed  $type
78
     * @return string
79
     */
80
    private function realType($type)
81
    {
82
        $phpType = gettype($type);
83
        return $phpType === 'object' ? get_class($type) : $phpType;
84
    }
85
86
    /**
87
     * @param $type
88
     * @throws \Exception
89
     */
90
    private function checkType($type)
91
    {
92
        if (! in_array($type, $this->allowedTypes)) {
93
            throw new \Exception('Type [' . $type . '] not allowed.');
94
        }
95
    }
96
}
97