service = $service; $this->notices = $notices; } /** * Capability that protects every route. * * @since 0.1.0 * * @return string */ protected function capability(): string { return Capabilities::MANAGE_CUSTOMERS; } /** * Arguments of the list route. * * @since 0.1.0 * * @return array> */ protected function collection_args(): array { return array_merge( $this->list_params( array_keys( NoticeRepository::ORDERBY ), 'id' ), array( 'status' => array( 'type' => 'string', 'default' => '', 'enum' => array( '', 'draft', 'published', 'archived' ), 'validate_callback' => 'rest_validate_request_arg', ), ) ); } /** * Lists notices. * * @since 0.1.0 * * @param WP_REST_Request $request Request. * @return array{items: array>, total: int} */ protected function query_items( WP_REST_Request $request ): array { return $this->notices->query( array( 'search' => $request['search'], 'status' => $request['status'], 'orderby' => $request['orderby'], 'order' => $request['order'], 'page' => $request['page'], 'per_page' => $request['per_page'], ) ); } /** * Lists notices and reports the number per status in a header. * * @since 0.1.0 * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function get_items( $request ) { $response = parent::get_items( $request ); $response->header( 'X-HostKhata-Status-Counts', wp_json_encode( $this->notices->status_counts() ) ); return $response; } /** * Finds one notice. * * @since 0.1.0 * * @param int $id Item id. * @return array|null */ protected function find_item( int $id ): ?array { return $this->notices->find( $id ); } /** * Creates a notice. * * @since 0.1.0 * * @param array $body Request body. * @return array|WP_Error */ protected function create_resource( array $body ) { return $this->service->create( $body ); } /** * Updates a notice. * * @since 0.1.0 * * @param int $id Item id. * @param array $body Request body. * @return array|WP_Error */ protected function update_resource( int $id, array $body ) { return $this->service->update( $id, $body ); } /** * Deletes a draft notice. * * @since 0.1.0 * * @param int $id Item id. * @return true|WP_Error */ protected function delete_resource( int $id ) { return $this->service->delete( $id ); } /** * Shapes a notice. * * @since 0.1.0 * * @param array $item Item from the repository. * @return array */ protected function present( array $item ): array { return array( 'id' => $item['id'], 'title' => $item['title'], 'body' => $item['body'], 'notice_type' => $item['notice_type'], 'audience' => $item['audience'], 'audience_ids' => $item['audience_ids'], 'starts_on' => substr( $item['starts_at_gmt'], 0, 10 ), 'ends_on' => substr( $item['ends_at_gmt'], 0, 10 ), 'send_email' => $item['send_email'], 'status' => $item['status'], 'read_count' => $this->notices->read_count( $item['id'] ), ); } /** * Message for a notice that does not exist. * * @since 0.1.0 * * @return string */ protected function not_found_message(): string { return __( 'Notice not found.', 'hostkhata' ); } }