Completed
Push — master ( 08dec9...d0d820 )
by Freek
13s queued 12s
created

AllowedSort   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
lcom 2
cbo 1
dl 0
loc 76
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A parseSortDirection() 0 4 2
A sort() 0 6 1
A field() 0 4 1
A custom() 0 4 1
A getName() 0 4 1
A isSort() 0 4 1
A getInternalName() 0 4 1
A defaultDirection() 0 13 2
1
<?php
2
3
namespace Spatie\QueryBuilder;
4
5
use Spatie\QueryBuilder\Enums\SortDirection;
6
use Spatie\QueryBuilder\Exceptions\InvalidDirection;
7
use Spatie\QueryBuilder\Sorts\Sort;
8
use Spatie\QueryBuilder\Sorts\SortsField;
9
10
class AllowedSort
11
{
12
    /** @var \Spatie\QueryBuilder\Sorts\Sort */
13
    protected $sortClass;
14
15
    /** @var string */
16
    protected $name;
17
18
    /** @var string */
19
    protected $defaultDirection;
20
21
    /** @var string */
22
    protected $internalName;
23
24
    public function __construct(string $name, Sort $sortClass, ?string $internalName = null)
25
    {
26
        $this->name = ltrim($name, '-');
27
28
        $this->sortClass = $sortClass;
29
30
        $this->defaultDirection = static::parseSortDirection($name);
31
32
        $this->internalName = $internalName ?? $this->name;
33
    }
34
35
    public static function parseSortDirection(string $name): string
36
    {
37
        return strpos($name, '-') === 0 ? SortDirection::DESCENDING : SortDirection::ASCENDING;
38
    }
39
40
    public function sort(QueryBuilder $query, ?bool $descending = null): void
41
    {
42
        $descending = $descending ?? ($this->defaultDirection === SortDirection::DESCENDING);
43
44
        ($this->sortClass)($query, $descending, $this->internalName);
45
    }
46
47
    public static function field(string $name, ?string $internalName = null): self
48
    {
49
        return new static($name, new SortsField, $internalName);
50
    }
51
52
    public static function custom(string $name, Sort $sortClass, ?string $internalName = null): self
53
    {
54
        return new static($name, $sortClass, $internalName);
55
    }
56
57
    public function getName(): string
58
    {
59
        return $this->name;
60
    }
61
62
    public function isSort(string $sortName): bool
63
    {
64
        return $this->name === $sortName;
65
    }
66
67
    public function getInternalName(): string
68
    {
69
        return $this->internalName;
70
    }
71
72
    public function defaultDirection(string $defaultDirection)
73
    {
74
        if (! in_array($defaultDirection, [
75
            SortDirection::ASCENDING,
76
            SortDirection::DESCENDING,
77
        ])) {
78
            throw InvalidDirection::make($defaultDirection);
79
        }
80
81
        $this->defaultDirection = $defaultDirection;
82
83
        return $this;
84
    }
85
}
86