| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Framework\QueryBuilder\Concerns; |
| 4 |
|
| 5 |
use Give\Framework\Database\DB; |
| 6 |
use Give\Framework\QueryBuilder\Clauses\OrderBy; |
| 7 |
use Give\Framework\QueryBuilder\Clauses\RawSQL; |
| 8 |
|
| 9 |
/** |
| 10 |
* @since 2.19.0 |
| 11 |
*/ |
| 12 |
trait OrderByStatement |
| 13 |
{ |
| 14 |
/** |
| 15 |
* @var OrderBy[] |
| 16 |
*/ |
| 17 |
protected $orderBys = []; |
| 18 |
|
| 19 |
/** |
| 20 |
* @param string $column |
| 21 |
* @param string $direction ASC|DESC |
| 22 |
* |
| 23 |
* @return $this |
| 24 |
*/ |
| 25 |
public function orderBy($column, $direction = 'ASC') |
| 26 |
{ |
| 27 |
$this->orderBys[] = new OrderBy($column, $direction); |
| 28 |
|
| 29 |
return $this; |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Add raw SQL Order By statement |
| 34 |
* |
| 35 |
* @since 4.0.0 |
| 36 |
* |
| 37 |
* @param $sql |
| 38 |
* @param ...$args |
| 39 |
* |
| 40 |
* @return $this |
| 41 |
*/ |
| 42 |
public function orderByRaw($sql, ...$args) |
| 43 |
{ |
| 44 |
$this->orderBys[] = new RawSQL($sql, $args); |
| 45 |
|
| 46 |
return $this; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* @return array|string[] |
| 51 |
*/ |
| 52 |
protected function getOrderBySQL() |
| 53 |
{ |
| 54 |
if (empty($this->orderBys)) { |
| 55 |
return []; |
| 56 |
} |
| 57 |
|
| 58 |
$orderBys = implode( |
| 59 |
', ', |
| 60 |
array_map(function ($order) { |
| 61 |
if ($order instanceof RawSQL) { |
| 62 |
return DB::prepare('%1s', $order->sql); |
| 63 |
} |
| 64 |
return DB::prepare('%1s %2s', $order->column, $order->direction); |
| 65 |
}, $this->orderBys) |
| 66 |
); |
| 67 |
|
| 68 |
|
| 69 |
return ['ORDER BY ' . $orderBys]; |
| 70 |
} |
| 71 |
} |
| 72 |
|