customers = $customers; $this->invoices = $invoices; $this->orders = $orders; $this->services = $services; $this->domains = $domains; } /** * Registers the route. * * @since 0.1.0 * * @return void */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'search' ), 'permission_callback' => Permissions::require_capability( Capabilities::ACCESS_APP ), 'args' => array( 'q' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } /** * Finds records that match the text. * * @since 0.1.0 * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function search( $request ): WP_REST_Response { $q = trim( (string) $request['q'] ); if ( strlen( $q ) < 2 ) { return rest_ensure_response( array( 'results' => array() ) ); } $args = array( 'search' => $q, 'per_page' => self::PER_KIND, ); $results = array(); if ( current_user_can( Capabilities::MANAGE_CUSTOMERS ) ) { foreach ( $this->customers->query( $args )['items'] as $item ) { $name = trim( $item['first_name'] . ' ' . $item['last_name'] ); $results[] = $this->hit( 'customer', $item['id'], '' !== $name ? $name : $item['company'], (string) $item['user_email'] ); } } if ( current_user_can( Capabilities::MANAGE_INVOICES ) ) { foreach ( $this->invoices->query( $args )['items'] as $item ) { $results[] = $this->hit( 'invoice', $item['id'], (string) $item['invoice_number'], (string) $item['customer_name'] ); } } if ( current_user_can( Capabilities::MANAGE_ORDERS ) ) { foreach ( $this->orders->query( $args )['items'] as $item ) { $results[] = $this->hit( 'order', $item['id'], (string) $item['order_number'], (string) $item['customer_name'] ); } foreach ( $this->services->query( $args )['items'] as $item ) { $results[] = $this->hit( 'service', $item['id'], '' !== (string) $item['domain'] ? (string) $item['domain'] : '#' . $item['id'], (string) $item['customer_name'] ); } foreach ( $this->domains->query( $args )['items'] as $item ) { $results[] = $this->hit( 'domain', $item['id'], (string) $item['domain_name'], (string) $item['customer_name'] ); } } return rest_ensure_response( array( 'results' => $results ) ); } /** * One search hit. * * @param string $type Kind of record. * @param int|string $id Record id. * @param string $title Main text. * @param string $subtitle Second line. * @return array */ private function hit( string $type, $id, string $title, string $subtitle ): array { return array( 'type' => $type, 'id' => (int) $id, 'title' => $title, 'subtitle' => $subtitle, ); } }