Completed
Push — master ( c9036e...5033a3 )
by Bartko
05:59
created

Validator::_validateLevels()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
ccs 11
cts 11
cp 1
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
    public function __construct(AdapterInterface $adapter)
21 9
    {
22
        $this->adapter = $adapter;
23 9
    }
24 9
25
    /**
26
     * @return AdapterInterface
27
     */
28
    private function _getAdapter()
29 9
    {
30
        return $this->adapter;
31 9
    }
32
33
    /**
34
     * @param NodeInfo $nodeInfo
35
     * @param array $_tree
36
     * @return array
37
     */
38
    private function _buildFlatTree(NodeInfo $nodeInfo, $_tree = array())
39 9
    {
40
        $children = $this->_getAdapter()
41 9
                         ->getChildrenNodeInfo($nodeInfo->getId());
42 9
43
        $_tree[] = $nodeInfo;
44 9
45
        foreach ($children as $child) {
46 9
            $_tree = $this->_buildFlatTree($child, $_tree);
47 9
        }
48
49
        return $_tree;
50 9
    }
51
52
    /**
53
     * @param array $tree
54
     * @return array
55
     */
56
    private function _validateLevels(array $tree)
57 9
    {
58
        $nodeIdVsLevel = array(0 => -1);
59 9
60
        foreach ($tree as &$nodeInfo) {
61 9
            $parentId = $nodeInfo->getParentId() ? $nodeInfo->getParentId() : 0;
62 9
63
            $nodeIdVsLevel[$nodeInfo->getId()] = $nodeIdVsLevel[$parentId] + 1;
64 9
65 9
            $currentLevel = $nodeInfo->getLevel();
66
            $expectedLevel = $nodeIdVsLevel[$parentId] + 1;
67 9
68 6
            if ($currentLevel != $expectedLevel) {
69 6
                $nodeInfo->setLevel($expectedLevel);
70
                $nodeInfo->setNeedUpdate(true);
71 9
72
                $this->isValid = false;
73
            }
74
        }
75 9
76
        return $tree;
77
    }
78
79
    /**
80
     * @param array $tree
81
     * @return array
82 9
     */
83
    private function _validateLeftIndexes(array $tree)
84 9
    {
85 9
        $expectedLeftIdx = -1;
86
        $prevLevel = 0;
87 9
88 9
        foreach ($tree as &$nodeInfo) {
89
            $currentLeftIdx = $nodeInfo->getLeft();
90 9
91 9
            if ($nodeInfo->getLevel() == $prevLevel) {
92 9
                $expectedLeftIdx += 2;
93 9
            } elseif ($nodeInfo->getLevel() > $prevLevel) {
94
                $expectedLeftIdx += 1;
95 6
            } else {
96
                $expectedLeftIdx += $prevLevel - $nodeInfo->getLevel() + 2;
97
            }
98 9
99 6
            if ($currentLeftIdx != $expectedLeftIdx) {
100 6
                $nodeInfo->setLeft($expectedLeftIdx);
101
                $nodeInfo->setNeedUpdate(true);
102 6
103
                $this->isValid = false;
104
            }
105 9
106
            $prevLevel = $nodeInfo->getLevel();
107
        }
108 9
109
        return $tree;
110
    }
111
112
    /**
113
     * @param array $tree
114
     * @return array
115 9
     */
116
    private function _validateRightIndexes(array $tree)
117 9
    {
118 9
        $prevLevel = -1;
119
        $endNodes = array();
120 9
121 9
        for ($x = count($tree); $x > 0; $x--) {
122 9
            $nodeInfo = $tree[$x - 1];
123 9
            if (-1 == $prevLevel || $prevLevel == $nodeInfo->getLevel()) {
124 9
                $expectedRightIdx = $nodeInfo->getLeft() + 1;
125 9
            } elseif ($prevLevel > $nodeInfo->getLevel()) {
126
                $currentLevel = $nodeInfo->getLevel();
127 9
128 9
                if (array_key_exists($currentLevel + 1, $endNodes)) {
129 9
                    $expectedRightIdx = $endNodes[$currentLevel + 1] + 1;
130
                    unset($endNodes[$currentLevel + 1]);
131 9
                } else {
132
                    $expectedRightIdx = $tree[$x]->getRight() + 1;
133
                }
134 6
            } else {
135
                $expectedRightIdx = $nodeInfo->getLeft() + 1;
136
            }
137 9
138
            $currentRightIdx = $nodeInfo->getRight();
139 9
140 6
            if ($currentRightIdx != $expectedRightIdx) {
141 6
                $nodeInfo->setRight($expectedRightIdx);
142 6
                $nodeInfo->setNeedUpdate(true);
143
                $tree[$x - 1] = $nodeInfo;
144 6
145
                $this->isValid = false;
146
            }
147 9
148 9
            if (!array_key_exists($nodeInfo->getLevel(), $endNodes)) {
149
                $endNodes[$nodeInfo->getLevel()] = $nodeInfo->getRight();
150
            }
151 9
152
            $prevLevel = $nodeInfo->getLevel();
153
        }
154 9
155
        return $tree;
156
    }
157 9
158
    public function isValid($rootNodeId)
159 9
    {
160 9
        $adapter = $this->_getAdapter();
161
162 9
        $adapter->beginTransaction();
163 9
        try {
164
            $adapter->lockTree();
165 9
166 9
            $result = $this->_isValid($rootNodeId);
167 9
168
            $adapter->commitTransaction();
169 9
        } catch (Exception $e) {
170
            $adapter->rollbackTransaction();
171 9
            throw $e;
172
        }
173
174 3
        return $result;
175
    }
176 3
177 3
    /**
178
     * @param $rootNodeId
179
     * @return bool True if tree is valid
180 3
     */
181
    protected function _isValid($rootNodeId)
182
    {
183
        $this->isValid = True;
184 3
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 3
188
        $tree = $this->_validateLevels($tree);
189
        $tree = $this->_validateLeftIndexes($tree);
190 3
        $tree = $this->_validateRightIndexes($tree);
191
192
        $this->tree = $tree;
193
194
        return $this->isValid;
195
    }
196
197
    public function rebuild($rootNodeId)
198
    {
199
        $adapter = $this->_getAdapter();
200
201
        $adapter->beginTransaction();
202
        try {
203
            $adapter->lockTree();
204
205
            $this->_isValid($rootNodeId);
206
207
            if ($this->isValid) {
208
                $adapter->commitTransaction();
209
                return;
210
            }
211
212
            foreach ($this->tree as $nodeInfo) {
213
                if ($nodeInfo->needUpdate()) {
214
                    $this->_getAdapter()
215
                         ->updateNodeMetadata($nodeInfo);
216
                }
217
            }
218
            $adapter->commitTransaction();
219
        } catch (Exception $e) {
220
            $adapter->rollbackTransaction();
221
            throw $e;
222
        }
223
    }
224
}
225