1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace DutchCodingCompany\CursorPagination; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
6
|
|
|
use Illuminate\Contracts\Support\Jsonable; |
7
|
|
|
use Illuminate\Support\Arr; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Encode and decode pagination cursors. |
11
|
|
|
*/ |
12
|
|
|
class Cursor implements Arrayable |
13
|
|
|
{ |
14
|
|
|
protected $after = null; |
15
|
|
|
|
16
|
|
|
public function __construct($after = null) |
17
|
|
|
{ |
18
|
|
|
$this->after = $after; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @return bool |
23
|
|
|
*/ |
24
|
|
|
public function isPresent() |
25
|
|
|
{ |
26
|
|
|
return $this->hasAfter(); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @return bool |
31
|
|
|
*/ |
32
|
|
|
public function hasAfter() |
33
|
|
|
{ |
34
|
|
|
return !is_null($this->after); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return mixed |
39
|
|
|
*/ |
40
|
|
|
public function getAfterCursor() |
41
|
|
|
{ |
42
|
|
|
return $this->after; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Decode cursor from query arguments. |
47
|
|
|
* |
48
|
|
|
* If no 'after' argument is provided or the contents are not a valid base64 string, |
49
|
|
|
* this will return empty array. That will effectively reset pagination, so the user gets the |
50
|
|
|
* first slice. |
51
|
|
|
* |
52
|
|
|
* @param array<string, mixed> $args |
53
|
|
|
*/ |
54
|
|
|
public static function decode(?array $args): Cursor |
55
|
|
|
{ |
56
|
|
|
$after = null; |
57
|
|
|
if ($cursor = Arr::get($args, 'after')) { |
58
|
|
|
$after = json_decode(base64_decode($cursor), true); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return new static($after); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Encode the given offset to make the implementation opaque. |
66
|
|
|
*/ |
67
|
|
|
public static function encode(array $data): string |
68
|
|
|
{ |
69
|
|
|
return base64_encode(json_encode($data)); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function toArray() |
73
|
|
|
{ |
74
|
|
|
return [ |
75
|
|
|
'after' => static::encode($this->after), |
76
|
|
|
]; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|