1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\Core\Model; |
6
|
|
|
|
7
|
|
|
use Shlinkio\Shlink\Core\Exception\ValidationException; |
8
|
|
|
|
9
|
|
|
use function explode; |
10
|
|
|
use function is_array; |
11
|
|
|
use function is_string; |
12
|
|
|
use function key; |
13
|
|
|
|
14
|
|
|
final class ShortUrlsOrdering |
15
|
|
|
{ |
16
|
|
|
public const ORDER_BY = 'orderBy'; |
17
|
|
|
private const DEFAULT_ORDER_DIRECTION = 'ASC'; |
18
|
|
|
|
19
|
|
|
private ?string $orderField = null; |
20
|
|
|
private string $orderDirection = self::DEFAULT_ORDER_DIRECTION; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @throws ValidationException |
24
|
|
|
*/ |
25
|
51 |
|
public static function fromRawData(array $query): self |
26
|
|
|
{ |
27
|
51 |
|
$instance = new self(); |
28
|
51 |
|
$instance->validateAndInit($query); |
29
|
|
|
|
30
|
51 |
|
return $instance; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @throws ValidationException |
35
|
|
|
*/ |
36
|
51 |
|
private function validateAndInit(array $data): void |
37
|
|
|
{ |
38
|
|
|
/** @var string|array|null $orderBy */ |
39
|
51 |
|
$orderBy = $data[self::ORDER_BY] ?? null; |
40
|
51 |
|
if ($orderBy === null) { |
41
|
41 |
|
return; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// FIXME Providing the ordering as array is considered deprecated. To be removed in v3.0.0 |
45
|
11 |
|
$isArray = is_array($orderBy); |
46
|
11 |
|
if (! $isArray && ! is_string($orderBy)) { |
|
|
|
|
47
|
|
|
throw ValidationException::fromArray([ |
48
|
|
|
'orderBy' => '"Order by" must be an array, string or null', |
49
|
|
|
]); |
50
|
|
|
} |
51
|
|
|
|
52
|
11 |
|
if (! $isArray) { |
53
|
9 |
|
$parts = explode('-', $orderBy); |
|
|
|
|
54
|
9 |
|
$this->orderField = $parts[0]; |
55
|
9 |
|
$this->orderDirection = $parts[1] ?? self::DEFAULT_ORDER_DIRECTION; |
56
|
|
|
} else { |
57
|
3 |
|
$this->orderField = key($orderBy); |
|
|
|
|
58
|
3 |
|
$this->orderDirection = $orderBy[$this->orderField]; |
59
|
|
|
} |
60
|
11 |
|
} |
61
|
|
|
|
62
|
1 |
|
public function orderField(): ?string |
63
|
|
|
{ |
64
|
1 |
|
return $this->orderField; |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
public function orderDirection(): string |
68
|
|
|
{ |
69
|
1 |
|
return $this->orderDirection; |
70
|
|
|
} |
71
|
|
|
|
72
|
1 |
|
public function hasOrderField(): bool |
73
|
|
|
{ |
74
|
1 |
|
return $this->orderField !== null; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|