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

Метод класса: WC_API_Customers{}

Хуков нет.

Возвращает

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

Использование

// protected - в коде основоного (родительского) или дочернего класса
$result = $this->validate_request( $id, $type, $context );
$id(int) (обязательный)
the customer ID
$type(строка) (обязательный)
the request type, unused because this method overrides the parent class
$context(строка) (обязательный)
the context of the request, either read, edit or delete

Заметки

Список изменений

С версии 2.1 Введена.

Код WC_API_Customers::validate_request() WC 8.7.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() ) );
	}
}