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 is_array; |
10
|
|
|
use function is_string; |
11
|
|
|
use function key; |
12
|
|
|
|
13
|
|
|
final class ShortUrlsOrdering |
14
|
|
|
{ |
15
|
|
|
public const ORDER_BY = 'orderBy'; |
16
|
|
|
private const DEFAULT_ORDER_DIRECTION = 'ASC'; |
17
|
|
|
|
18
|
|
|
private ?string $orderField = null; |
19
|
|
|
private string $orderDirection = self::DEFAULT_ORDER_DIRECTION; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @throws ValidationException |
23
|
|
|
*/ |
24
|
49 |
|
public static function fromRawData(array $query): self |
25
|
|
|
{ |
26
|
49 |
|
$instance = new self(); |
27
|
49 |
|
$instance->validateAndInit($query); |
28
|
|
|
|
29
|
49 |
|
return $instance; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @throws ValidationException |
34
|
|
|
*/ |
35
|
49 |
|
private function validateAndInit(array $data): void |
36
|
|
|
{ |
37
|
|
|
/** @var string|array|null $orderBy */ |
38
|
49 |
|
$orderBy = $data[self::ORDER_BY] ?? null; |
39
|
49 |
|
if ($orderBy === null) { |
40
|
39 |
|
return; |
41
|
|
|
} |
42
|
|
|
|
43
|
10 |
|
$isArray = is_array($orderBy); |
44
|
10 |
|
if (! $isArray && $orderBy !== null && ! is_string($orderBy)) { |
|
|
|
|
45
|
|
|
throw ValidationException::fromArray([ |
46
|
|
|
'orderBy' => '"Order by" must be an array, string or null', |
47
|
|
|
]); |
48
|
|
|
} |
49
|
|
|
|
50
|
10 |
|
$this->orderField = $isArray ? key($orderBy) : $orderBy; |
|
|
|
|
51
|
10 |
|
$this->orderDirection = $isArray ? $orderBy[$this->orderField] : self::DEFAULT_ORDER_DIRECTION; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function orderField(): ?string |
55
|
|
|
{ |
56
|
|
|
return $this->orderField; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function orderDirection(): string |
60
|
|
|
{ |
61
|
|
|
return $this->orderDirection; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function hasOrderField(): bool |
65
|
|
|
{ |
66
|
|
|
return $this->orderField !== null; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|