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

Order   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 55
ccs 15
cts 15
cp 1
c 0
b 0
f 0
rs 10
wmc 7
lcom 1
cbo 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A orderBy() 0 6 2
A addOrderBy() 0 6 2
A prepareOrderBy() 0 11 3
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