Completed
Push — master ( 33d412...b764b5 )
by Ben
02:26
created

BranchCollection::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Thinktomorrow\Vine\Branch;
4
5
use Thinktomorrow\Vine\VineException;
6
7
/**
8
 * Class BranchCollection
9
 *
10
 * @property array $branches
11
 */
12
class BranchCollection extends ArrayCollection
13
{
14 42
    public function __construct(array $branches = [])
15
    {
16 42
        self::validateBranches($branches);
17
18 42
        $this->branches = $branches;
19 42
    }
20
21 15
    public function hasBranches()
22
    {
23 15
        return (!empty($this->branches) && count($this->branches) > 0);
24
    }
25
26 18
    public function push(Branch $branch)
27
    {
28 18
        $this->branches[] = $branch;
29
30 18
        return $this;
31
    }
32
33 3
    public function __get($key)
34
    {
35 3
        if(isset($this->$key)) return $this->$key;
36
37
        throw VineException::unknownBranchCollectionAttribute($key);
38
    }
39
40 42
    public static function validateBranches($branches)
41
    {
42 42
        foreach($branches as $branch)
43
        {
44 15
            if(!$branch instanceof Branch)
45 10
            {
46 5
                throw VineException::requiredAsBranch($branch);
47
            }
48 28
        }
49 42
    }
50
51
    public function flatten()
52
    {
53 6
        $flatten = array_reduce($this->branches,function($carry,$branch){
54 6
            return array_merge($carry,$this->flattenRecursive($branch,0));
55 6
        },[]);
56
57 6
        return new static($flatten);
58
    }
59
60 6
    protected function flattenRecursive(Branch $branch, $level = 0)
61
    {
62 6
        $children = $branch->branches;
63
64
        // Remove the children reference
65 6
        $output = [new Branch($branch->key,$branch->value,$branch->label)];
66
67 6
        foreach($children as $child) $output = array_merge($output,$this->flattenRecursive($child,$level+1));
68
69 6
        return $output;
70
    }
71
}
72