Factory   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 9
c 3
b 0
f 1
lcom 0
cbo 1
dl 0
loc 55
ccs 29
cts 29
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
D fromArray() 0 42 9
1
<?php
2
3
/*
4
 * This file is part of the kaloa/util package.
5
 *
6
 * For full copyright and license information, please view the LICENSE file
7
 * that was distributed with this source code.
8
 */
9
10
namespace Kaloa\Util\Tree;
11
12
use Exception;
13
use Kaloa\Util\Tree\Node;
14
15
/**
16
 *
17
 */
18
final class Factory
19
{
20
    /**
21
     * Creates a tree structure from an array and returns the root element
22
     *
23
     * $a has to be a list of (key, parent_key, value) triplets. Keys will not
24
     * be preserved, they are only used to define the initial tree hierarchy.
25
     * The value part may be any kind of object, array or scalar value.
26
     *
27
     * @param  array $array
28
     * @return Node Root element
29
     */
30 4
    public function fromArray(array $array)
31
    {
32 4
        $root   = new Node(null);
33 4
        $map    = array();
34 4
        $map[0] = $root;
35
36
        // Create an entry in $map for every item in $a
37 4
        foreach ($array as $element) {
38 4
            if (3 !== count($element)) {
39 1
                throw new Exception('Each array must have 3 elements.');
40
            }
41
42 3
            $map[$element[0]] = new Node($element[2]);
43 3
        }
44
45
        //
46 3
        foreach ($array as $element) {
47 3
            if (empty($element[1])) {
48 2
                $element[1] = 0;
49 2
            }
50
51 3
            $found = false;
52 3
            $i     = 0;
53 3
            $keys  = array_keys($map);
54 3
            $cnt   = count($keys);
55 3
            while (!$found && $i < $cnt) {
56 3
                if ($keys[$i] === $element[1]) {
57 2
                    $map[$keys[$i]]->addChild($map[$element[0]]);
58 2
                    $found = true;
59 2
                } else {
60 3
                    $i++;
61
                }
62 3
            }
63 3
            if (!$found) {
64
                // Error
65 1
                throw new Exception('Data structure does not seem to be consistent. '
66 1
                        . 'Key "' . $element[1] . '" could not be found.');
67
            }
68 2
        }
69
70 2
        return $root;
71
    }
72
}
73