registry = $registry; } /** * Registers hooks. * * @return void */ public function register(): void { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Registers REST routes. * * @return void */ public function register_routes(): void { register_rest_route( SettingsController::ROUTE_NAMESPACE, '/conditions/(?P[a-z0-9_]+)/search', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'search' ), 'permission_callback' => array( $this, 'can_edit_rules' ), 'args' => array( 'search' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), ), ), ) ); register_rest_route( SettingsController::ROUTE_NAMESPACE, '/conditions/(?P[a-z0-9_]+)/labels', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'labels' ), 'permission_callback' => array( $this, 'can_edit_rules' ), 'args' => array( 'values' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ), 'required' => true, ), ), ), ) ); } /** * Returns the labels of saved values that still exist, so the editors can * name picked items and flag the ones that were deleted. * * @param WP_REST_Request $request Request. * @phpstan-param WP_REST_Request> $request * @return WP_REST_Response|WP_Error */ public function labels( WP_REST_Request $request ) { $condition = $this->registry->get( (string) $request->get_param( 'type' ) ); if ( ! $condition instanceof SearchableCondition ) { return new WP_Error( 'yangra_conditional_not_searchable', __( 'This condition has no items to search.', 'yangra-conditional' ), array( 'status' => 404 ) ); } $values = array_values( array_map( 'sanitize_text_field', array_map( 'strval', (array) $request->get_param( 'values' ) ) ) ); // An object, even when empty, so the editors can read it the same way. return new WP_REST_Response( array( 'labels' => (object) $condition->labels( $values ) ) ); } /** * Anyone who can edit content can set rules (on blocks), and classic menu * editors need `edit_theme_options`. The results are term names and the * display names of authors with published posts, which are already public. * * @return bool */ public function can_edit_rules(): bool { return current_user_can( 'edit_posts' ) || current_user_can( 'edit_theme_options' ); } /** * Returns the items matching the search. * * @param WP_REST_Request $request Request. * @phpstan-param WP_REST_Request> $request * @return WP_REST_Response|WP_Error */ public function search( WP_REST_Request $request ) { $condition = $this->registry->get( (string) $request->get_param( 'type' ) ); if ( ! $condition instanceof SearchableCondition ) { return new WP_Error( 'yangra_conditional_not_searchable', __( 'This condition has no items to search.', 'yangra-conditional' ), array( 'status' => 404 ) ); } return new WP_REST_Response( array( 'items' => $condition->search( (string) $request->get_param( 'search' ) ) ) ); } }