Completed
Push — master ( df4deb...f531b1 )
by Pavel
02:22
created

SortableBehavior::getCondition()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
ccs 10
cts 10
cp 1
rs 9.2
cc 4
eloc 7
nc 2
nop 0
crap 4
1
<?php
2
/**
3
 * Behavior for Yii2 to support sorting in ActiveRecord models
4
 *
5
 * @link https://github.com/inblank/yii2-sortable
6
 * @copyright Copyright (c) 2016 Pavel Aleksandrov <[email protected]>
7
 * @license http://opensource.org/licenses/MIT
8
 */
9
namespace inblank\sortable;
10
11
use Yii;
12
use yii\base\Behavior;
13
use yii\db\ActiveRecord;
14
use yii\db\Expression;
15
use yii\db\QueryBuilder;
16
17
/**
18
 * Behavior for Yii2 to support sorting in ActiveRecord models
19
 *
20
 * @property ActiveRecord $owner
21
 */
22
class SortableBehavior extends Behavior
23
{
24
    /**
25
     * Attribute to store the sort order of records
26
     * @var string
27
     */
28
    public $sortAttribute = 'sort';
29
30
    /**
31
     * The list of attributes used as sorting conditions of the records.
32
     * null mean no condition and sort all records
33
     * One attribute can be define as string.
34
     * @var array|string
35
     */
36
    public $conditionAttributes = null;
37
38
    /**
39
     * Maximal sort index
40
     * @var int
41
     */
42
    protected $_max;
43
    /**
44
     * Rendered sorting position
45
     * @var array
46
     */
47
    protected $_condition;
48
49
    /**
50
     * @inheritdoc
51
     */
52 8
    public function events()
53
    {
54
        return [
55 8
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
56 8
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
57 8
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
58 8
        ];
59
    }
60
61
    /** Before validate event */
62 3
    public function beforeValidate()
63
    {
64 3
        if ($this->owner->getIsNewRecord()) {
65
            // added new record always on top
66 1
            $this->owner->{$this->sortAttribute} = $this->owner->find()->andWhere($this->getCondition())->count();
67 1
        } else {
68
            // prevent direct change of sort field
69 2
            $this->owner->{$this->sortAttribute} = $this->owner->getOldAttribute($this->sortAttribute);
70
        }
71 3
    }
72
73
    /** After update event */
74 2
    public function afterUpdate($event)
75
    {
76 2
        $oldCondition = [];
77 2
        $currentCondition = [];
78
        /** @var ActiveRecord $owner */
79 2
        $owner = $this->owner;
80 2
        foreach ((array)$this->conditionAttributes as $attribute) {
81 2
            if (!$owner->hasAttribute($attribute)) {
82 1
                continue;
83
            }
84 2
            $oldCondition[$attribute] = $currentCondition[$attribute] = $owner->getAttribute($attribute);
85 2
            if (array_key_exists($attribute, $event->changedAttributes)) {
86 1
                $oldCondition[$attribute] = $event->changedAttributes[$attribute];
87 1
            }
88 2
        }
89 2
        if (array_diff($currentCondition, $oldCondition) != []) {
90
            // condition was changed
91
            /** @var ActiveRecord $changedModel */
92 1
            $changedModel = Yii::createObject($owner->className());
93 1
            $changedModel->setAttributes($oldCondition, false);
94
            // recalculate old model range
95 1
            $changedModel->recalculateSort();
96
            // move model to top in new model range
97 1
            $owner->updateAttributes(['sort' => $owner->find()->andWhere($this->getCondition())->count() - 1]);
98 1
        }
99 2
    }
100
101
    /** After delete event */
102 1
    public function afterDelete()
103
    {
104 1
        $owner = $this->owner;
105 1
        $condition = $this->getCondition();
106 1
        $condition[] = ['>', 'sort', $owner->{$this->sortAttribute}];
107 1
        $owner->updateAllCounters([$this->sortAttribute => -1], $condition);
108 1
    }
109
110
    /**
111
     * Move record to the specific sorting position
112
     * @param int $position new sorting position
113
     */
114 4
    public function moveToPosition($position)
115
    {
116 4
        $this->sortChange($position - $this->owner->{$this->sortAttribute});
117 4
    }
118
119
    /**
120
     * Move record to the top of sorting order
121
     */
122 1
    public function moveToTop()
123
    {
124 1
        $this->moveToPosition(PHP_INT_MAX);
125 1
    }
126
127
    /**
128
     * Move record to the bottom of sorting order
129
     */
130 2
    public function moveToBottom()
131
    {
132 2
        $this->moveToPosition(0);
133 2
    }
134
135
    /**
136
     * Move records
137
     * @param int $value
138
     */
139 5
    public function sortChange($value)
140
    {
141 5
        if ($value == 0) {
142 1
            return;
143
        }
144 5
        $owner = $this->owner;
145 5
        $condition = $this->getCondition();
146 5
        $newSort = $owner->{$this->sortAttribute} + $value;
147 5
        if ($value > 0) {
148
            // move up
149 4
            $max = $this->getMaxSort();
150 4
            if ($owner->{$this->sortAttribute} === $max) {
151 1
                return;
152
            }
153 3
            if ($newSort >= $max) {
154 2
                $newSort = $max;
155 2
            }
156 3
            $condition[] = [">", 'sort', $owner->{$this->sortAttribute}];
157 3
            $condition[] = ["<=", 'sort', $newSort];
158 3
            $counterChanger = -1;
159 3
        } else {
160
            // move down
161 4
            if ($owner->{$this->sortAttribute} === 0) {
162 1
                return;
163
            }
164 4
            if ($newSort < 0) {
165 1
                $newSort = 0;
166 1
            }
167 4
            $condition[] = ['<', 'sort', $owner->{$this->sortAttribute}];
168 4
            $condition[] = ['>=', 'sort', $newSort];
169 4
            $counterChanger = 1;
170
        }
171 5
        $owner->updateAllCounters([$this->sortAttribute => $counterChanger], $condition);
172 5
        $owner->updateAttributes(['sort' => $newSort]);
173 5
    }
174
175
    /**
176
     * Recalculate sorting
177
     */
178 2
    public function recalculateSort()
179
    {
180 2
        $owner = $this->owner;
181 2
        $db = $this->owner->getDb();
182 2
        $builder = new QueryBuilder($db);
183
184 2
        $orderFields = ['sort' => 'asc'];
185 2
        foreach ($owner->primaryKey() as $field) {
186 2
            if ($field != 'sort') {
187 2
                $orderFields[$field] = 'asc';
188 2
            }
189 2
        }
190
        // recalculate sort
191 2
        $query = $builder->update(
192 2
                $owner->tableName(),
193 2
                [$this->sortAttribute => new Expression('(@sortingCount:=(@sortingCount+1))')],
194 2
                $this->getCondition(),
195
                $params
196 2
            ) . ' ' . $builder->buildOrderBy($orderFields);
197 2
        $db->createCommand('set @sortingCount=-1;' . $query, $params)->execute();
198
        // update in current record
199 2
        if (!$owner->getIsNewRecord()) {
200 1
            $owner->{$this->sortAttribute} = $owner->findOne($owner->getPrimaryKey())->{$this->sortAttribute};
201 1
        }
202 2
    }
203
204
    /**
205
     * Get maximal sort index
206
     */
207 4
    public function getMaxSort()
208
    {
209 4
        if ($this->_max === null) {
210 4
            $this->_max = $this->owner->find()->andWhere($this->getCondition())->count() - 1;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->owner->find()->an...ndition())->count() - 1 can also be of type double. However, the property $_max is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
211 4
        }
212 4
        return $this->_max;
213
    }
214
215
    /**
216
     * Get WHERE condition for sort change query
217
     * @return array
218
     */
219 8
    protected function getCondition()
220
    {
221 8
        if ($this->_condition === null) {
222 8
            $this->_condition = ['and'];
223 8
            foreach ((array)$this->conditionAttributes as $attribute) {
224 8
                if ($this->owner->hasAttribute($attribute)) {
225 8
                    $this->_condition[] = [$attribute => $this->owner->$attribute];
226 8
                }
227 8
            }
228 8
        }
229 8
        return $this->_condition;
230
    }
231
232
}
233