OrderByTrait::orderBy()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 6
nop 2
dl 0
loc 19
rs 9.6111
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Janisbiz\LightOrm\Dms\MySQL\QueryBuilder\Traits;
4
5
use Janisbiz\LightOrm\Dms\MySQL\Enum\ConditionEnum;
6
use Janisbiz\LightOrm\Dms\MySQL\Enum\KeywordEnum;
7
use Janisbiz\LightOrm\Dms\MySQL\QueryBuilder\QueryBuilderException;
8
9
trait OrderByTrait
10
{
11
    /**
12
     * @var array
13
     */
14
    protected $orderBy = [];
15
16
    /**
17
     * @param string|array $orderBy
18
     * @param string $keyword
19
     *
20
     * @throws QueryBuilderException
21
     * @return $this
22
     */
23
    public function orderBy($orderBy, string $keyword = KeywordEnum::ASC)
24
    {
25
        if (empty($orderBy)) {
26
            throw new QueryBuilderException('You must pass $orderBy to orderBy method!');
27
        }
28
29
        if (!\in_array($keyword, [KeywordEnum::ASC, KeywordEnum::DESC])) {
30
            throw new QueryBuilderException(\sprintf('Invalid $keyword "%s" for orderBy!', $keyword));
31
        }
32
33
        if (!\is_array($orderBy)) {
34
            $orderBy = [$orderBy];
35
        }
36
37
        foreach ($orderBy as $orderByColumn) {
38
            $this->orderBy[] = \sprintf('%s %s', $orderByColumn, $keyword);
39
        }
40
41
        return $this;
42
    }
43
44
    /**
45
     * @return null|string
46
     */
47
    protected function buildOrderByQueryPart(): ?string
48
    {
49
        return empty($this->orderBy)
50
            ? null
51
            : \sprintf('%s %s', ConditionEnum::ORDER_BY, \implode(', ', $this->orderBy))
52
        ;
53
    }
54
}
55