FixedOrderByTrait::applyEmptyOrderByParams()   B
last analyzed

Complexity

Conditions 6
Paths 10

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 18
cp 0
rs 8.9457
c 0
b 0
f 0
cc 6
nc 10
nop 1
crap 42
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember/
7
 */
8
9
namespace flipbox\craft\ember\queries;
10
11
use craft\db\Connection as CraftConnection;
12
use craft\db\FixedOrderExpression;
13
use craft\db\QueryAbortedException;
14
use craft\helpers\StringHelper;
15
use yii\base\Exception;
16
use yii\db\Connection;
17
18
/**
19
 * @author Flipbox Factory <[email protected]>
20
 * @since 2.0.0
21
 *
22
 * @method void traitApplyEmptyOrderByParams(Connection $db)
23
 */
24
trait FixedOrderByTrait
25
{
26
    use OrderByTrait {
27
        applyEmptyOrderByParams as traitApplyEmptyOrderByParams;
28
    }
29
30
    /**
31
     * @var bool Whether results should be returned in the order specified by [[domain]].
32
     */
33
    public $fixedOrder = false;
34
35
    /**
36
     * @return string
37
     */
38
    abstract protected function fixedOrderColumn(): string;
39
40
    /**
41
     * @param Connection $db
42
     * @throws Exception
43
     * @throws QueryAbortedException
44
     */
45
    protected function applyEmptyOrderByParams(Connection $db)
46
    {
47
        if ($this->fixedOrder) {
48
            $values = $this->{$this->fixedOrderColumn()};
49
            if (!is_array($values)) {
50
                $values = is_string($values) ? StringHelper::split($values) : [$values];
51
            }
52
53
            if (empty($values)) {
54
                throw new QueryAbortedException;
55
            }
56
57
            // Order the elements in the exact order that the Search service returned them in
58
            if (!$db instanceof CraftConnection) {
59
                throw new Exception('The database connection doesn\'t support fixed ordering.');
60
            }
61
62
            $this->orderBy = [new FixedOrderExpression($this->fixedOrderColumn(), $values, $db)];
63
        } else {
64
            $this->traitApplyEmptyOrderByParams($db);
65
        }
66
    }
67
}
68