Completed
Push — master ( 467d47...6f2bb4 )
by Anton
14s
created

Order::prepareOrderBy()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
nc 3
dl 0
loc 11
ccs 7
cts 7
cp 1
c 0
b 0
f 0
cc 3
eloc 7
nop 0
crap 3
rs 9.4285
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Db\Query\Traits;
12
13
/**
14
 * Order Trait
15
 *
16
 * Required for:
17
 *  - Select Builder
18
 *  - Update Builder
19
 *  - Delete Builder
20
 *
21
 * @package  Bluz\Db\Query\Traits
22
 * @author   Anton Shevchuk
23
 */
24
trait Order
25
{
26
    /**
27
     * @var array
28
     */
29
    protected $orderBy = [];
30
31
    /**
32
     * Specifies an ordering for the query results
33
     * Replaces any previously specified orderings, if any
34
     *
35
     * @param  string $sort  Sort expression
36
     * @param  string $order Sort direction (ASC or DESC)
37
     *
38
     * @return $this
39
     */
40 1
    public function orderBy(string $sort, string $order = 'ASC')
41
    {
42 1
        $order = 'ASC' === strtoupper($order) ? 'ASC' : 'DESC';
43 1
        $this->orderBy = [$sort => $order];
44 1
        return $this;
45
    }
46
47
    /**
48
     * Adds an ordering to the query results
49
     *
50
     * @param  string $sort  Sort expression
51
     * @param  string $order Sort direction (ASC or DESC)
52
     *
53
     * @return $this
54
     */
55 1
    public function addOrderBy(string $sort, string $order = 'ASC')
56
    {
57 1
        $order = 'ASC' === strtoupper($order) ? 'ASC' : 'DESC';
58 1
        $this->orderBy[$sort] = $order;
59 1
        return $this;
60
    }
61
62
    /**
63
     * Prepare string to apply it inside SQL query
64
     *
65
     * @return string
66
     */
67 8
    protected function prepareOrderBy() : string
68
    {
69 8
        if (empty($this->orderBy)) {
70 7
            return '';
71
        }
72 1
        $orders = [];
73 1
        foreach ($this->orderBy as $column => $order) {
74 1
            $orders[] = $column . ' ' . $order;
75
        }
76 1
        return ' ORDER BY ' . implode(', ', $orders);
77
    }
78
}
79