OrderScope::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Sfneal\Scopes;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Scope;
8
9
class OrderScope implements Scope
10
{
11
    /**
12
     * @var string Name of the column that identifies order
13
     */
14
    private string $column;
15
16
    /**
17
     * @var string Direction to order results (asc or desc)
18
     */
19
    private string $direction;
20
21
    /**
22
     * @var bool Raw OrderBy clause to order null values last
23
     */
24
    private bool $raw;
25
26
    /**
27
     * OrderOrderScope constructor.
28
     *
29
     * @param  string  $column
30
     * @param  string  $direction
31
     * @param  bool  $raw
32
     */
33
    public function __construct(string $column = 'order', string $direction = 'desc', bool $raw = false)
34
    {
35
        $this->column = $column;
36
        $this->direction = ucwords($direction);
37
        $this->raw = $raw;
38
    }
39
40
    /**
41
     * Apply the scope to a given Eloquent query builder.
42
     *
43
     * @param  Builder  $builder
44
     * @param  Model  $model
45
     * @return void
46
     */
47
    public function apply(Builder $builder, Model $model): void
48
    {
49
        // Use '-' prefix to order NULL values last
50
        if ($this->raw) {
51
            $builder->orderByRaw("-`{$this->column}` desc");
52
        }
53
54
        // Standard orderBy clause
55
        $builder->orderBy($this->column, $this->direction);
56
    }
57
}
58