WC_API_Resource::validate_request()protectedWC 2.1

Validate the request by checking:

1) the ID is a valid integer
2) the ID returns a valid post object and matches the provided post type
3) the current user has the proper permissions to read/edit/delete the post

Method of the class: WC_API_Resource{}

No Hooks.

Return

Int|WP_Error. valid post ID or WP_Error if any of the checks fails

Usage

// protected - for code of main (parent) or child class
$result = $this->validate_request( $id, $type, $context );
$id(string|int) (required)
the post ID
$type(string) (required)
the post type, either shop_order, shop_coupon, or product
$context(string) (required)
the context of the request, either read, edit or delete

Changelog

Since 2.1 Introduced.

WC_API_Resource::validate_request() code WC 7.7.0

protected function validate_request( $id, $type, $context ) {

	if ( 'shop_order' === $type || 'shop_coupon' === $type ) {
		$resource_name = str_replace( 'shop_', '', $type );
	} else {
		$resource_name = $type;
	}

	$id = absint( $id );

	// validate ID
	if ( empty( $id ) ) {
		return new WP_Error( "woocommerce_api_invalid_{$resource_name}_id", sprintf( __( 'Invalid %s ID', 'woocommerce' ), $type ), array( 'status' => 404 ) );
	}

	// only custom post types have per-post type/permission checks
	if ( 'customer' !== $type ) {

		$post = get_post( $id );

		// for checking permissions, product variations are the same as the product post type
		$post_type = ( 'product_variation' === $post->post_type ) ? 'product' : $post->post_type;

		// validate post type
		if ( $type !== $post_type ) {
			return new WP_Error( "woocommerce_api_invalid_{$resource_name}", sprintf( __( 'Invalid %s', 'woocommerce' ), $resource_name ), array( 'status' => 404 ) );
		}

		// validate permissions
		switch ( $context ) {

			case 'read':
				if ( ! $this->is_readable( $post ) ) {
					return new WP_Error( "woocommerce_api_user_cannot_read_{$resource_name}", sprintf( __( 'You do not have permission to read this %s', 'woocommerce' ), $resource_name ), array( 'status' => 401 ) );
				}
				break;

			case 'edit':
				if ( ! $this->is_editable( $post ) ) {
					return new WP_Error( "woocommerce_api_user_cannot_edit_{$resource_name}", sprintf( __( 'You do not have permission to edit this %s', 'woocommerce' ), $resource_name ), array( 'status' => 401 ) );
				}
				break;

			case 'delete':
				if ( ! $this->is_deletable( $post ) ) {
					return new WP_Error( "woocommerce_api_user_cannot_delete_{$resource_name}", sprintf( __( 'You do not have permission to delete this %s', 'woocommerce' ), $resource_name ), array( 'status' => 401 ) );
				}
				break;
		}
	}

	return $id;
}