NestedSetsQueryBehavior::roots()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * @link https://github.com/creocoder/yii2-nested-sets
4
 * @copyright Copyright (c) 2015 Alexander Kochetov
5
 * @license http://opensource.org/licenses/BSD-3-Clause
6
 */
7
8
namespace creocoder\nestedsets;
9
10
use yii\base\Behavior;
11
use yii\db\Expression;
12
13
/**
14
 * NestedSetsQueryBehavior
15
 *
16
 * @property \yii\db\ActiveQuery $owner
17
 *
18
 * @author Alexander Kochetov <[email protected]>
19
 */
20
class NestedSetsQueryBehavior extends Behavior
21
{
22
    /**
23
     * Gets the root nodes.
24
     * @return \yii\db\ActiveQuery the owner
25
     */
26
    public function roots()
27 6
    {
28
        $model = new $this->owner->modelClass();
29 6
30
        $this->owner
31 6
            ->andWhere([$model->leftAttribute => 1])
32 6
            ->addOrderBy([$model->primaryKey()[0] => SORT_ASC]);
33 6
34
        return $this->owner;
35 6
    }
36
37
    /**
38
     * Gets the leaf nodes.
39 6
     * @return \yii\db\ActiveQuery the owner
40
     */
41
    public function leaves()
42
    {
43
        $model = new $this->owner->modelClass();
44
        $db = $model->getDb();
45
46 2
        $columns = [$model->leftAttribute => SORT_ASC];
47
48 2
        if ($model->treeAttribute !== false) {
49 2
            $columns = [$model->treeAttribute => SORT_ASC] + $columns;
50
        }
51 2
52
        $this->owner
53 2
            ->andWhere([$model->rightAttribute => new Expression($db->quoteColumnName($model->leftAttribute) . '+ 1')])
54 2
            ->addOrderBy($columns);
55 2
56
        return $this->owner;
57 2
    }
58
}
59