OrderBy::getExpression()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 13
cts 13
cp 1
rs 9.6333
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * @link https://github.com/vuongxuongminh/yii2-searchable
4
 * @copyright Copyright (c) 2019 Vuong Xuong Minh
5
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
6
 */
7
8
namespace vxm\searchable\expression;
9
10
use yii\db\Expression as DbExpression;
11
use yii\db\ExpressionInterface;
12
13
/**
14
 * Class OrderBy support add order by search result for make result have been order by exact ids.
15
 *
16
 * @author Vuong Minh <[email protected]>
17
 * @since 1.0.0
18
 */
19
class OrderBy extends Expression
20
{
21
22
    /**
23
     * @inheritDoc
24
     * @return ExpressionInterface|OrderBy
25
     */
26 4
    public function getExpression(): ExpressionInterface
27
    {
28 4
        $position = 1;
29 4
        $cases = ['CASE'];
30 4
        $params = [];
31 4
        $searchableKey = $this->searchableKey();
32
33 4
        foreach ($this->ids as $id) {
34 4
            $paramName = ":sob{$position}";
35 4
            $cases[] = "WHEN {$searchableKey} = {$paramName} THEN {$position}";
36 4
            $params[$paramName] = $id;
37 4
            $position++;
38
        }
39
40 4
        $cases[] = "ELSE {$position}";
41 4
        $cases[] = 'END ASC';
42
43 4
        return new DbExpression(implode(' ', $cases), $params);
44
    }
45
46
47
}
48