Completed
Push — develop ( 4f051c...c7250c )
by Bartko
07:21 queued 05:04
created

Validator::_validateLevels()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 14
cts 14
cp 1
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 12
nc 5
nop 1
crap 4
1
<?php
2
namespace StefanoTree\NestedSet\Validator;
3
4
use Exception;
5
use StefanoTree\NestedSet\Adapter\AdapterInterface;
6
use StefanoTree\NestedSet\NodeInfo;
7
8
class Validator
9
    implements ValidatorInterface
0 ignored issues
show
Coding Style introduced by
The implements keyword must be on the same line as the class name
Loading history...
10
{
11
    private $isValid = true;
12
13
    private $tree = array();
14
15
    private $adapter = null;
16
17
    /**
18
     * @param AdapterInterface $adapter
19
     */
20 3
    public function __construct(AdapterInterface $adapter)
21
    {
22 3
        $this->adapter = $adapter;
23 3
    }
24
25
    /**
26
     * @return AdapterInterface
27
     */
28 3
    private function _getAdapter()
29
    {
30 3
        return $this->adapter;
31
    }
32
33
    /**
34
     * @param NodeInfo $nodeInfo
35
     * @param array $_tree
36
     * @return array
37
     */
38 3
    private function _buildFlatTree(NodeInfo $nodeInfo, $_tree = array())
39
    {
40 3
        $children = $this->_getAdapter()
41 3
                         ->getChildrenNodeInfo($nodeInfo->getId());
42
43 3
        $_tree[] = $nodeInfo;
44
45 3
        foreach ($children as $child) {
46 3
            $_tree = $this->_buildFlatTree($child, $_tree);
47 3
        }
48
49 3
        return $_tree;
50
    }
51
52
    /**
53
     * @param array $tree
54
     * @return array
55
     */
56 3
    private function _validateLevels(array $tree)
57
    {
58 3
        $nodeIdVsLevel = array(0 => -1);
59
60 3
        foreach ($tree as &$nodeInfo) {
61 3
            $parentId = $nodeInfo->getParentId() ? $nodeInfo->getParentId() : 0;
62
63 3
            $nodeIdVsLevel[$nodeInfo->getId()] = $nodeIdVsLevel[$parentId] + 1;
64
65 3
            $currentLevel = $nodeInfo->getLevel();
66 3
            $expectedLevel = $nodeIdVsLevel[$parentId] + 1;
67
68 3
            if ($currentLevel != $expectedLevel) {
69 2
                $nodeInfo->setLevel($expectedLevel);
70 2
                $nodeInfo->setNeedUpdate(true);
71
72 2
                $this->isValid = false;
73 2
            }
74 3
        }
75
76 3
        return $tree;
77
    }
78
79
    /**
80
     * @param array $tree
81
     * @return array
82
     */
83 3
    private function _validateLeftIndexes(array $tree)
84
    {
85 3
        $expectedLeftIdx = -1;
86 3
        $prevLevel = 0;
87
88 3
        foreach ($tree as &$nodeInfo) {
89 3
            $currentLeftIdx = $nodeInfo->getLeft();
90
91 3
            if ($nodeInfo->getLevel() == $prevLevel) {
92 3
                $expectedLeftIdx += 2;
93 3
            } elseif ($nodeInfo->getLevel() > $prevLevel) {
94 3
                $expectedLeftIdx += 1;
95 3
            } else {
96 2
                $expectedLeftIdx += $prevLevel - $nodeInfo->getLevel() + 2;
97
            }
98
99 3
            if ($currentLeftIdx != $expectedLeftIdx) {
100 2
                $nodeInfo->setLeft($expectedLeftIdx);
101 2
                $nodeInfo->setNeedUpdate(true);
102
103 2
                $this->isValid = false;
104 2
            }
105
106 3
            $prevLevel = $nodeInfo->getLevel();
107 3
        }
108
109 3
        return $tree;
110
    }
111
112
    /**
113
     * @param array $tree
114
     * @return array
115
     */
116 3
    private function _validateRightIndexes(array $tree)
117
    {
118 3
        $prevLevel = -1;
119 3
        $endNodes = array();
120
121 3
        for ($x = count($tree); $x > 0; $x--) {
122 3
            $nodeInfo = $tree[$x - 1];
123 3
            if (-1 == $prevLevel || $prevLevel == $nodeInfo->getLevel()) {
124 3
                $expectedRightIdx = $nodeInfo->getLeft() + 1;
125 3
            } elseif ($prevLevel > $nodeInfo->getLevel()) {
126 3
                $currentLevel = $nodeInfo->getLevel();
127
128 3
                if (array_key_exists($currentLevel + 1, $endNodes)) {
129 3
                    $expectedRightIdx = $endNodes[$currentLevel + 1] + 1;
130 3
                    unset($endNodes[$currentLevel + 1]);
131 3
                } else {
132
                    $expectedRightIdx = $tree[$x]->getRight() + 1;
133
                }
134 3
            } else {
135 2
                $expectedRightIdx = $nodeInfo->getLeft() + 1;
136
            }
137
138 3
            $currentRightIdx = $nodeInfo->getRight();
139
140 3
            if ($currentRightIdx != $expectedRightIdx) {
141 2
                $nodeInfo->setRight($expectedRightIdx);
142 2
                $nodeInfo->setNeedUpdate(true);
143 2
                $tree[$x - 1] = $nodeInfo;
144
145 2
                $this->isValid = false;
146 2
            }
147
148 3
            if (!array_key_exists($nodeInfo->getLevel(), $endNodes)) {
149 3
                $endNodes[$nodeInfo->getLevel()] = $nodeInfo->getRight();
150 3
            }
151
152 3
            $prevLevel = $nodeInfo->getLevel();
153 3
        }
154
155 3
        return $tree;
156
    }
157
158 2
    public function isValid($rootNodeId)
159
    {
160 2
        $adapter = $this->_getAdapter();
161
162 2
        $adapter->beginTransaction();
163
        try {
164 2
            $adapter->lockTree();
165
166 2
            $result = $this->_isValid($rootNodeId);
167
168 2
            $adapter->commitTransaction();
169 2
        } catch (Exception $e) {
170
            $adapter->rollbackTransaction();
171
            throw $e;
172
        }
173
174 2
        return $result;
175
    }
176
177
    /**
178
     * @param $rootNodeId
179
     * @return bool True if tree is valid
180
     */
181 3
    protected function _isValid($rootNodeId)
182
    {
183 3
        $this->isValid = True;
184
185 3
        $rootNodeInfo = $this->_getAdapter()->getNodeInfo($rootNodeId);
186 3
        $tree = $this->_buildFlatTree($rootNodeInfo);
0 ignored issues
show
Bug introduced by
It seems like $rootNodeInfo defined by $this->_getAdapter()->getNodeInfo($rootNodeId) on line 185 can be null; however, StefanoTree\NestedSet\Va...dator::_buildFlatTree() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
187
188 3
        $tree = $this->_validateLevels($tree);
189 3
        $tree = $this->_validateLeftIndexes($tree);
190 3
        $tree = $this->_validateRightIndexes($tree);
191
192 3
        $this->tree = $tree;
193
194 3
        return $this->isValid;
195
    }
196
197 1
    public function rebuild($rootNodeId)
198
    {
199 1
        $adapter = $this->_getAdapter();
200
201 1
        $adapter->beginTransaction();
202
        try {
203 1
            $adapter->lockTree();
204
205 1
            $this->_isValid($rootNodeId);
206
207 1
            if ($this->isValid) {
208
                $adapter->commitTransaction();
209
                return;
210
            }
211
212 1
            foreach ($this->tree as $nodeInfo) {
213 1
                if ($nodeInfo->needUpdate()) {
214 1
                    $this->_getAdapter()
215 1
                         ->updateNodeMetadata($nodeInfo);
216 1
                }
217 1
            }
218 1
            $adapter->commitTransaction();
219 1
        } catch (Exception $e) {
220
            $adapter->rollbackTransaction();
221
            throw $e;
222
        }
223 1
    }
224
}
225