WC_API_Customers::validate_request()protectedWC 2.1

Validate the request by checking:

1) the ID is a valid integer
2) the ID returns a valid WP_User
3) the current user has the proper permissions

Method of the class: WC_API_Customers{}

No Hooks.

Return

Int|WP_Error. valid user 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(int) (required)
the customer ID
$type(string) (required)
the request type, unused because this method overrides the parent class
$context(string) (required)
the context of the request, either read, edit or delete

Notes

Changelog

Since 2.1 Introduced.

WC_API_Customers::validate_request() code WC 8.9.0

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

	try {
		$id = absint( $id );

		// validate ID
		if ( empty( $id ) ) {
			throw new WC_API_Exception( 'woocommerce_api_invalid_customer_id', __( 'Invalid customer ID', 'woocommerce' ), 404 );
		}

		// non-existent IDs return a valid WP_User object with the user ID = 0
		$customer = new WP_User( $id );

		if ( 0 === $customer->ID ) {
			throw new WC_API_Exception( 'woocommerce_api_invalid_customer', __( 'Invalid customer', 'woocommerce' ), 404 );
		}

		// validate permissions
		switch ( $context ) {

			case 'read':
				if ( ! current_user_can( 'list_users' ) ) {
					throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_customer', __( 'You do not have permission to read this customer', 'woocommerce' ), 401 );
				}
				break;

			case 'edit':
				if ( ! wc_rest_check_user_permissions( 'edit', $customer->ID ) ) {
					throw new WC_API_Exception( 'woocommerce_api_user_cannot_edit_customer', __( 'You do not have permission to edit this customer', 'woocommerce' ), 401 );
				}
				break;

			case 'delete':
				if ( ! wc_rest_check_user_permissions( 'delete', $customer->ID ) ) {
					throw new WC_API_Exception( 'woocommerce_api_user_cannot_delete_customer', __( 'You do not have permission to delete this customer', 'woocommerce' ), 401 );
				}
				break;
		}

		return $id;
	} catch ( WC_API_Exception $e ) {
		return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
	}
}