WC_API_Customers::validate_request( integer $id, string $type, string $context )

Validate the request by checking:


Description Description

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

See also See also


Top ↑

Parameters Parameters

$id

(Required) the customer ID

$type

(Required) the request type, unused because this method overrides the parent class

$context

(Required) the context of the request, either read, edit or delete


Top ↑

Return Return

(int|WP_Error) valid user ID or WP_Error if any of the checks fails


Top ↑

Source Source

File: includes/legacy/api/v2/class-wc-api-customers.php

	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() ) );
		}
	}

Top ↑

Changelog Changelog

Changelog
Version Description
2.1 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.