Completed
Push — master ( 1e376d...b0060a )
by Changwan
05:50
created

OrderByExpression   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 56
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0
wmc 9
lcom 1
cbo 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A orderBy() 0 5 1
A andOrderBy() 0 11 3
A toSql() 0 11 4
A getBindings() 0 4 1
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 9
    public function orderBy($name, $asc = true)
26
    {
27 9
        $this->orders = [];
28 9
        return $this->andOrderBy($name, $asc);
29
    }
30
31
    /**
32
     * @param string|array $name
33
     * @param bool $asc
34
     * @return static
35
     */
36 10
    public function andOrderBy($name, $asc = true)
37
    {
38 10
        if (is_array($name)) {
39 1
            foreach ($name as $key => $asc) {
40 1
                $this->orders[] = [$key, $asc];
41 1
            }
42 1
        } else {
43 10
            $this->orders[] = [$name, $asc];
44
        }
45 10
        return $this;
46
    }
47
    
48
    /**
49
     * {@inheritdoc}
50
     */
51 11
    public function toSql()
52
    {
53 11
        if (count($this->orders) === 0) {
54 1
            return '';
55
        }
56 10
        $parts = [];
57 10
        foreach ($this->orders as $order) {
58 10
            $parts[] = "`{$order[0]}`" . ($order[1] ? '' : ' DESC');
59 10
        }
60 10
        return 'ORDER BY ' . Helper::arrayImplode(", ", $parts);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 11
    public function getBindings()
67
    {
68 11
        return [];
69
    }
70
}
71