class-wp-rest-test-search-handler.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * REST API: WP_REST_Test_Search_Handler class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. */
  8. /**
  9. * Test class extending WP_REST_Search_Handler
  10. */
  11. class WP_REST_Test_Search_Handler extends WP_REST_Search_Handler {
  12. protected $items = array();
  13. public function __construct( $amount = 10 ) {
  14. $this->type = 'test';
  15. $this->subtypes = array( 'test_first_type', 'test_second_type' );
  16. $this->items = array();
  17. for ( $i = 1; $i <= $amount; $i++ ) {
  18. $subtype = $i > $amount / 2 ? 'test_second_type' : 'test_first_type';
  19. $this->items[ $i ] = (object) array(
  20. 'test_id' => $i,
  21. 'test_title' => sprintf( 'Title %d', $i ),
  22. 'test_url' => sprintf( home_url( '/tests/%d' ), $i ),
  23. 'test_type' => $subtype,
  24. );
  25. }
  26. }
  27. public function search_items( WP_REST_Request $request ) {
  28. $subtypes = $request[ WP_REST_Search_Controller::PROP_SUBTYPE ];
  29. if ( in_array( WP_REST_Search_Controller::TYPE_ANY, $subtypes, true ) ) {
  30. $subtypes = $this->subtypes;
  31. }
  32. $results = array();
  33. foreach ( $subtypes as $subtype ) {
  34. $results = array_merge( $results, wp_list_filter( array_values( $this->items ), array( 'test_type' => $subtype ) ) );
  35. }
  36. $results = wp_list_sort( $results, 'test_id', 'DESC' );
  37. $number = (int) $request['per_page'];
  38. $offset = (int) $request['per_page'] * ( (int) $request['page'] - 1 );
  39. $total = count( $results );
  40. $results = array_slice( $results, $offset, $number );
  41. return array(
  42. self::RESULT_IDS => wp_list_pluck( $results, 'test_id' ),
  43. self::RESULT_TOTAL => $total,
  44. );
  45. }
  46. public function prepare_item( $id, array $fields ) {
  47. $test = $this->items[ $id ];
  48. $data = array();
  49. if ( in_array( WP_REST_Search_Controller::PROP_ID, $fields, true ) ) {
  50. $data[ WP_REST_Search_Controller::PROP_ID ] = (int) $test->test_id;
  51. }
  52. if ( in_array( WP_REST_Search_Controller::PROP_TITLE, $fields, true ) ) {
  53. $data[ WP_REST_Search_Controller::PROP_TITLE ] = $test->test_title;
  54. }
  55. if ( in_array( WP_REST_Search_Controller::PROP_URL, $fields, true ) ) {
  56. $data[ WP_REST_Search_Controller::PROP_URL ] = $test->test_url;
  57. }
  58. if ( in_array( WP_REST_Search_Controller::PROP_TYPE, $fields, true ) ) {
  59. $data[ WP_REST_Search_Controller::PROP_TYPE ] = $this->type;
  60. }
  61. if ( in_array( WP_REST_Search_Controller::PROP_SUBTYPE, $fields, true ) ) {
  62. $data[ WP_REST_Search_Controller::PROP_SUBTYPE ] = $test->test_type;
  63. }
  64. return $data;
  65. }
  66. public function prepare_item_links( $id ) {
  67. return array();
  68. }
  69. }