Passed
Push — master ( e97712...5fe6af )
by Yuichi
02:30
created

TreeStructureTrait::addTree()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 13
ccs 12
cts 12
cp 1
crap 4
rs 9.2
1
<?php
2
namespace Sonar\Common;
3
use Exception;
4
5
trait TreeStructureTrait
6
{
7
    protected $tree;
8
9 2
    public function getTree()
10
    {
11 2
        return $this->tree;
12
    }
13 1
    public function initTree()
14
    {
15 1
        $this->tree = [];
16 1
    }
17 7
    public function addTreeStructure($data)
18
    {
19 7
        $tree = isset($this->tree) ? $this->tree : [];
20
21 7
        foreach ( $data as $rec ) {
22 7
            if ( is_object($rec) === false ) throw new Exception('data record must be object.');
23 6
            if ( isset($rec->id) === false ) throw new Exception('data record object does not have property => "id".');
24 5
            if ( isset($rec->parent_id) === false || ! $rec->parent_id ) {
25 5
                $rec->children = [];
26 5
                $tree[$rec->id] = $rec;
27 5
            } else {
28 5
                $this->addTree($tree,$rec);
29
            }
30 5
        }
31 5
        $this->tree = $tree;
32 5
    }
33 5
    protected function addTree(&$tree,$data)
34
    {
35 5
        foreach ( $tree as $id => &$rec ) {
36 5
            if ( $data->parent_id == $id ) {
37 5
                $data->children = [];
38 5
                $rec->children[$data->id] = $data;
39 5
                return;
40 5
            } elseif ( count($rec->children) ) {
41 5
                $this->addTree($rec->children,$data);
42 5
            }
43 5
            unset($rec);
44 5
        }
45 5
    }
46 4
    public function mergeCount($count_data)
47
    {
48 4
        $tree = isset($this->tree) ? $this->tree : [];
49 4
        foreach ( $tree as &$rec ) {
50 4
            foreach ( $count_data as $count ) {
51 4
                if ( isset($rec->id) === false ) throw new Exception('data record object does not have property => "id".');
52 4
                if ( isset($count->id) === false ) throw new Exception('count data record object does not have property => "id".');
53 2
                if ( isset($count->count) === false ) throw new Exception('count data record object does not have property => "count".');
54 1
                if ( $rec->id == $count->id ) {
55 1
                    $rec->count = $count->count;
56 1
                }
57 1
            }
58 1
        }
59 1
        $this->tree = $tree;
60 1
    }
61
}
62