| 1 |
<?php |
| 2 |
|
| 3 |
namespace LearnPress\MCP\Support; |
| 4 |
|
| 5 |
defined( 'ABSPATH' ) || exit; |
| 6 |
|
| 7 |
/** |
| 8 |
* Pagination helpers for LearnPress MCP list tools. |
| 9 |
* |
| 10 |
* Single home for pagination input clamping, output math, and the pagination / |
| 11 |
* list-output JSON schemas shared by the read abilities. |
| 12 |
*/ |
| 13 |
class Pagination { |
| 14 |
|
| 15 |
/** |
| 16 |
* Sanitize a page number (minimum 1). |
| 17 |
* |
| 18 |
* @param mixed $value Raw page value. |
| 19 |
* |
| 20 |
* @return int |
| 21 |
*/ |
| 22 |
public static function page( $value ): int { |
| 23 |
$page = absint( $value ); |
| 24 |
return $page > 0 ? $page : 1; |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* Sanitize a per-page number and clamp to a safe range (1..100, default 10). |
| 29 |
* |
| 30 |
* @param mixed $value Raw per-page value. |
| 31 |
* |
| 32 |
* @return int |
| 33 |
*/ |
| 34 |
public static function per_page( $value ): int { |
| 35 |
$per_page = absint( $value ); |
| 36 |
if ( $per_page < 1 ) { |
| 37 |
$per_page = 10; |
| 38 |
} |
| 39 |
if ( $per_page > 100 ) { |
| 40 |
$per_page = 100; |
| 41 |
} |
| 42 |
|
| 43 |
return $per_page; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Calculate total pages from total item count. |
| 48 |
* |
| 49 |
* @param int $total_items Total items. |
| 50 |
* @param int $per_page Items per page. |
| 51 |
* |
| 52 |
* @return int |
| 53 |
*/ |
| 54 |
public static function total_pages( int $total_items, int $per_page ): int { |
| 55 |
return $per_page > 0 ? (int) ceil( $total_items / $per_page ) : 0; |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Pagination schema used by list abilities. |
| 60 |
* |
| 61 |
* @return array |
| 62 |
*/ |
| 63 |
public static function schema(): array { |
| 64 |
return array( |
| 65 |
'type' => 'object', |
| 66 |
'additionalProperties' => false, |
| 67 |
'required' => array( 'page', 'per_page', 'total_items', 'total_pages' ), |
| 68 |
'properties' => array( |
| 69 |
'page' => array( 'type' => 'integer' ), |
| 70 |
'per_page' => array( 'type' => 'integer' ), |
| 71 |
'total_items' => array( 'type' => 'integer' ), |
| 72 |
'total_pages' => array( 'type' => 'integer' ), |
| 73 |
), |
| 74 |
); |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Build a list response schema with pagination. |
| 79 |
* |
| 80 |
* @param array $item_schema Schema for each list item. |
| 81 |
* |
| 82 |
* @return array |
| 83 |
*/ |
| 84 |
public static function list_output( array $item_schema ): array { |
| 85 |
return array( |
| 86 |
'type' => 'object', |
| 87 |
'additionalProperties' => false, |
| 88 |
'required' => array( 'items', 'pagination' ), |
| 89 |
'properties' => array( |
| 90 |
'items' => array( |
| 91 |
'type' => 'array', |
| 92 |
'items' => $item_schema, |
| 93 |
), |
| 94 |
'pagination' => self::schema(), |
| 95 |
), |
| 96 |
); |
| 97 |
} |
| 98 |
} |
| 99 |
|