OrderByExpression::orderBy()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Database\Query\Expression;
3
4
use Wandu\Database\Contracts\ExpressionInterface;
5
use Wandu\Database\Support\Helper;
6
7
/**
8
 * OrderByItem = '`' name '`' 'DESC' ? | OrderByItem ', ' OrderByItem
9
 * OrderByExpression = 'ORDER BY ' OrderByItem
10
 *
11
 * @example ORDER BY `id`
12
 * @example ORDER BY `id` DESC
13
 * @example ORDER BY `id`, `user_id` DESC
14
 */
15
class OrderByExpression implements ExpressionInterface
16
{
17
    /** @var array */
18
    protected $orders = [];
19
20
    /**
21
     * @param string|array $name
22
     * @param bool $asc
23
     * @return static
24
     */
25 11
    public function orderBy($name, $asc = true)
26
    {
27 11
        $this->orders = [];
28 11
        return $this->andOrderBy($name, $asc);
29
    }
30
31
    /**
32
     * @param string|array $name
33
     * @param bool $asc
34
     * @return static
35
     */
36 12
    public function andOrderBy($name, $asc = true)
37
    {
38 12
        if (is_array($name)) {
39 1
            foreach ($name as $key => $asc) {
40 1
                $this->orders[] = [$key, $asc];
41
            }
42
        } else {
43 12
            $this->orders[] = [$name, $asc];
44
        }
45 12
        return $this;
46
    }
47
    
48
    /**
49
     * {@inheritdoc}
50
     */
51 15
    public function toSql()
52
    {
53 15
        if (count($this->orders) === 0) {
54 1
            return '';
55
        }
56 14
        $parts = [];
57 14
        foreach ($this->orders as $order) {
58 14
            $parts[] = Helper::normalizeName($order[0]) . ($order[1] ? '' : ' DESC');
59
        }
60 14
        return 'ORDER BY ' . Helper::arrayImplode(", ", $parts);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 15
    public function getBindings()
67
    {
68 15
        return [];
69
    }
70
}
71