\d+)', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_scan' ), 'permission_callback' => array( __CLASS__, 'can_edit' ), ), array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'save_scan' ), 'permission_callback' => array( __CLASS__, 'can_edit' ), 'args' => array( 'title' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'status' => array( 'type' => 'string', 'enum' => array( 'draft', 'publish' ), ), 'graph' => array( 'type' => 'object', 'required' => true, ), ), ), ) ); } /** * Only users who may edit this scan can read or save it. * * @param WP_REST_Request $request Request. * @return true|WP_Error */ public static function can_edit( WP_REST_Request $request ) { $post = get_post( (int) $request['id'] ); if ( ! $post || Post_Type::POST_TYPE !== $post->post_type ) { return new WP_Error( 'funnelfork_not_found', __( 'Quickscan not found.', 'funnelfork' ), array( 'status' => 404 ) ); } if ( ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'funnelfork_forbidden', __( 'You are not allowed to edit this quickscan.', 'funnelfork' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * GET a scan. * * @param WP_REST_Request $request Request. */ public static function get_scan( WP_REST_Request $request ): WP_REST_Response { return rest_ensure_response( self::prepare( (int) $request['id'] ) ); } /** * POST (save) a scan. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public static function save_scan( WP_REST_Request $request ) { $id = (int) $request['id']; $update = array( 'ID' => $id ); if ( null !== $request['title'] ) { $update['post_title'] = $request['title']; } if ( null !== $request['status'] ) { if ( 'publish' === $request['status'] && ! current_user_can( 'publish_post', $id ) ) { return new WP_Error( 'funnelfork_forbidden', __( 'You are not allowed to publish this quickscan.', 'funnelfork' ), array( 'status' => 403 ) ); } $update['post_status'] = $request['status']; } if ( count( $update ) > 1 ) { $result = wp_update_post( wp_slash( $update ), true ); if ( is_wp_error( $result ) ) { return $result; } } funnelfork_save_graph( $id, (array) $request['graph'] ); return rest_ensure_response( self::prepare( $id ) ); } /** * Response shape for one scan. * * @param int $id Scan ID. */ private static function prepare( int $id ): array { $post = get_post( $id ); return array( 'id' => $id, 'title' => $post->post_title, 'status' => $post->post_status, 'graph' => funnelfork_get_graph( $id ), ); } }