\WP_REST_Server::READABLE, 'callback' => array( __CLASS__, 'list_tables' ), 'permission_callback' => array( __CLASS__, 'can_read' ), ) ); register_rest_route( self::NAMESPACE_, '/tables/(?P\d+)', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => array( __CLASS__, 'get_table' ), 'permission_callback' => array( __CLASS__, 'can_manage' ), 'args' => array( 'id' => array( 'type' => 'integer', 'required' => true, 'sanitize_callback' => 'absint', 'validate_callback' => function ( $value ) { return is_numeric( $value ) && (int) $value > 0; }, ), ), ) ); } /** * The table list feeds the table picker of the Nitida Table block, so everyone who can write posts may read it. * It holds only the number, name and size of each table: every table is published content that any * [nitida_table] shortcode in a post can show, and the plugin has no private tables. */ public static function can_read() { return current_user_can( 'edit_posts' ); } /** Details of one table (description, edit link) need the table-management capability from the settings. */ public static function can_manage() { return current_user_can( Settings::capability() ); } public static function edit_url( $id ) { return admin_url( 'admin.php?page=nitida-tables&action=edit&id=' . (int) $id ); } public static function list_tables() { $out = array(); foreach ( Store::ids() as $id ) { $t = Store::get( $id ); if ( ! $t ) { continue; } $out[] = array( 'id' => (int) $t['id'], 'name' => (string) $t['name'], 'rows' => count( $t['data'] ), 'cols' => count( $t['data'][0] ), 'modified' => (int) $t['modified'], ); } return rest_ensure_response( $out ); } public static function get_table( \WP_REST_Request $request ) { $t = Store::get( (int) $request['id'] ); if ( ! $t ) { return new \WP_Error( 'nitida_tables_not_found', __( 'Table not found.', 'nitida-tables' ), array( 'status' => 404 ) ); } return rest_ensure_response( array( 'id' => (int) $t['id'], 'name' => (string) $t['name'], 'description' => (string) $t['description'], 'rows' => count( $t['data'] ), 'cols' => count( $t['data'][0] ), 'modified' => (int) $t['modified'], 'edit_url' => self::edit_url( $t['id'] ), ) ); } }