-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCursorPaginator.php
More file actions
61 lines (49 loc) · 1.96 KB
/
Copy pathCursorPaginator.php
File metadata and controls
61 lines (49 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
namespace DirectoryTree\OpenSearchScoutDriver;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\Cursor;
use Illuminate\Pagination\CursorPaginator as BaseCursorPaginator;
use UnexpectedValueException;
class CursorPaginator extends BaseCursorPaginator
{
/**
* The cursor parameter containing OpenSearch hit sort values.
*/
public const SEARCH_AFTER_PARAMETER = '_search_after';
/**
* @param array<string, array<int, mixed>> $searchAfter
*/
protected array $searchAfter = [];
/**
* Resolve the cursor from the current request or explicit value.
*/
public static function resolveCursor(Cursor|string|null $cursor, string $cursorName = 'cursor'): ?Cursor
{
if ($cursor instanceof Cursor) {
return $cursor;
}
if (is_string($cursor)) {
return Cursor::fromEncoded($cursor);
}
return BaseCursorPaginator::resolveCurrentCursor($cursorName);
}
/**
* Get the cursor parameters for a given item.
*/
public function getParametersForItem(mixed $item): array
{
/** @var Model $item */
$item = $item instanceof JsonResource ? $item->resource : $item;
if (! $item instanceof Model) {
throw new UnexpectedValueException('OpenSearch cursor pagination only supports Eloquent models.');
}
if (! method_exists($item, 'getScoutKey')) {
throw new UnexpectedValueException('OpenSearch cursor pagination only supports Eloquent models that use the Laravel Scout Searchable trait.');
}
if (! array_key_exists($key = $item->getScoutKey(), $this->searchAfter)) {
throw new UnexpectedValueException(sprintf('Unable to resolve OpenSearch search_after values for model [%s] with scout key [%s].', $item::class, $key));
}
return [self::SEARCH_AFTER_PARAMETER => $this->searchAfter[$key]];
}
}