Completed
Pull Request — master (#74)
by Daniel
02:13
created

Header::isSortAscending()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Grid\View;
6
7
use Psi\Component\Grid\GridContext;
8
9
class Header
10
{
11
    private $name;
12
    private $label;
13
    private $gridContext;
14
    private $sortField;
15
    private $template;
16
17
    public function __construct(
18
        GridContext $gridContext,
19
        string $name,
20
        string $label,
21
        string $template,
22
        string $sortField = null
23
    )
24
    {
25
        $this->name = $name;
26
        $this->label = $label;
27
        $this->gridContext = $gridContext;
28
        $this->sortField = $sortField;
29
        $this->template = $template;
30
    }
31
32
    public function getName()
33
    {
34
        return $this->name;
35
    }
36
37
    public function getLabel() 
38
    {
39
        return $this->label;
40
    }
41
42
    public function getTemplate() 
43
    {
44
        return $this->template;
45
    }
46
47
    public function isSorted(): bool
48
    {
49
        $ordering = $this->gridContext->getOrderings();
50
51
        return isset($ordering[$this->name]);
52
    }
53
54
    public function isSortAscending(): bool
55
    {
56
        if (false === $this->isSorted()) {
57
            throw new \RuntimeException(sprintf(
58
                'Cannot determine if sort is ascending when the field ("%s") is not sorted.',
59
                $this->name
60
            ));
61
        }
62
63
        return $this->gridContext->getOrderings()[$this->name] === 'asc';
64
    }
65
66
    public function getSortField(): string
67
    {
68
        return $this->sortField;
69
    }
70
71
    public function canBeSorted(): bool
72
    {
73
        return null !== $this->sortField;
74
    }
75
76
    public function getUrlParametersForSort($order = 'asc')
77
    {
78
        $gridContext = $this->gridContext->getUrlParameters();
79
        $gridContext['orderings'] = [
80
            $this->name => $order,
81
        ];
82
83
        return $gridContext;
84
    }
85
}
86