|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types = 1); |
| 4 | +namespace Rebing\GraphQL\Support; |
| 5 | + |
| 6 | +use GraphQL\Type\Definition\ObjectType; |
| 7 | +use GraphQL\Type\Definition\Type as GraphQLType; |
| 8 | +use Illuminate\Contracts\Pagination\CursorPaginator; |
| 9 | +use Illuminate\Support\Collection; |
| 10 | +use Rebing\GraphQL\Support\Facades\GraphQL; |
| 11 | + |
| 12 | +class CursorPaginationType extends ObjectType |
| 13 | +{ |
| 14 | + public function __construct(string $typeName, ?string $customName = null) |
| 15 | + { |
| 16 | + $name = $customName ?: $typeName . 'CursorPagination'; |
| 17 | + |
| 18 | + $underlyingType = GraphQL::type($typeName); |
| 19 | + |
| 20 | + $config = [ |
| 21 | + 'name' => $name, |
| 22 | + 'fields' => $this->getPaginationFields($underlyingType), |
| 23 | + ]; |
| 24 | + |
| 25 | + if (isset($underlyingType->config['model'])) { |
| 26 | + $config['model'] = $underlyingType->config['model']; |
| 27 | + } |
| 28 | + |
| 29 | + parent::__construct($config); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @return array<string, array<string,mixed>> |
| 34 | + */ |
| 35 | + protected function getPaginationFields(GraphQLType $underlyingType): array |
| 36 | + { |
| 37 | + return [ |
| 38 | + 'data' => [ |
| 39 | + 'type' => GraphQLType::nonNull(GraphQLType::listOf(GraphQLType::nonNull($underlyingType))), |
| 40 | + 'description' => 'List of items on the current page', |
| 41 | + 'resolve' => function (CursorPaginator $data): Collection { |
| 42 | + return $data->getCollection(); |
| 43 | + }, |
| 44 | + ], |
| 45 | + 'per_page' => [ |
| 46 | + 'type' => GraphQLType::nonNull(GraphQLType::int()), |
| 47 | + 'description' => 'Number of items returned per page', |
| 48 | + 'resolve' => function (CursorPaginator $data): int { |
| 49 | + return $data->perPage(); |
| 50 | + }, |
| 51 | + 'selectable' => false, |
| 52 | + ], |
| 53 | + 'previous_cursor' => [ |
| 54 | + 'type' => GraphQLType::string(), |
| 55 | + 'description' => 'Previous page cursor', |
| 56 | + 'resolve' => function (CursorPaginator $data): ?string { |
| 57 | + return $data->previousCursor()?->encode(); |
| 58 | + }, |
| 59 | + 'selectable' => false, |
| 60 | + ], |
| 61 | + 'next_cursor' => [ |
| 62 | + 'type' => GraphQLType::string(), |
| 63 | + 'description' => 'Next page cursor', |
| 64 | + 'resolve' => function (CursorPaginator $data): ?string { |
| 65 | + return $data->nextCursor()?->encode(); |
| 66 | + }, |
| 67 | + 'selectable' => false, |
| 68 | + ], |
| 69 | + ]; |
| 70 | + } |
| 71 | +} |
0 commit comments