1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Psi\Component\Grid; |
6
|
|
|
|
7
|
|
|
final class GridOptions |
8
|
|
|
{ |
9
|
|
|
private $variant; |
10
|
|
|
private $page; |
11
|
|
|
private $pageSize; |
12
|
|
|
private $orderings; |
13
|
|
|
|
14
|
|
|
public function __construct(array $options) |
15
|
|
|
{ |
16
|
|
|
$defaults = [ |
17
|
|
|
'page_size' => 50, |
18
|
|
|
'current_page' => 0, |
19
|
|
|
'orderings' => [], |
20
|
|
|
'variant' => null, |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
View Code Duplication |
if ($diff = array_diff(array_keys($options), array_keys($defaults))) { |
|
|
|
|
24
|
|
|
throw new \InvalidArgumentException(sprintf( |
25
|
|
|
'Invalid grid options "%s". Valid options: "%s"', |
26
|
|
|
implode('", "', $diff), implode('", "', array_keys($defaults)) |
27
|
|
|
)); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$options = array_merge($defaults, $options); |
31
|
|
|
$orderings = array_map(function ($order) { |
32
|
|
|
$order = strtolower($order); |
33
|
|
|
|
34
|
|
|
if (false === in_array($order, [ 'asc', 'desc' ])) { |
35
|
|
|
throw new \InvalidArgumentException(sprintf( |
36
|
|
|
'Order must be either "asc" or "desc" got "%s"', |
37
|
|
|
$order |
38
|
|
|
)); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
return $order; |
42
|
|
|
}, $options['orderings']); |
43
|
|
|
|
44
|
|
|
$this->currentPage = $options['current_page']; |
|
|
|
|
45
|
|
|
$this->pageSize = $options['page_size']; |
46
|
|
|
$this->orderings = $orderings; |
47
|
|
|
$this->variant = $options['variant']; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function getCurrentPage(): int |
51
|
|
|
{ |
52
|
|
|
return $this->currentPage; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function getPageSize(): int |
56
|
|
|
{ |
57
|
|
|
return $this->pageSize; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function getPageOffset(): int |
61
|
|
|
{ |
62
|
|
|
return $this->currentPage * $this->pageSize; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function getOrderings(): array |
66
|
|
|
{ |
67
|
|
|
return $this->orderings; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function getVariant() |
71
|
|
|
{ |
72
|
|
|
return $this->variant; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.