WC_Discounts::validate_coupon_usage_limit()protectedWC 3.2.0

Ensure coupon usage limit is valid or throw exception.

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

Хуков нет.

Возвращает

true|false.

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

// protected - в коде основоного (родительского) или дочернего класса
$result = $this->validate_coupon_usage_limit( $coupon );
$coupon(WC_Coupon) (обязательный)
Coupon data.

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

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

Код WC_Discounts::validate_coupon_usage_limit() WC 8.7.0

protected function validate_coupon_usage_limit( $coupon ) {
	if ( ! $coupon->get_usage_limit() ) {
		return true;
	}
	$usage_count           = $coupon->get_usage_count();
	$data_store            = $coupon->get_data_store();
	$tentative_usage_count = is_callable( array( $data_store, 'get_tentative_usage_count' ) ) ? $data_store->get_tentative_usage_count( $coupon->get_id() ) : 0;
	if ( $usage_count + $tentative_usage_count < $coupon->get_usage_limit() ) {
		// All good.
		return true;
	}
	// Coupon usage limit is reached. Let's show as informative error message as we can.
	if ( 0 === $tentative_usage_count ) {
		// No held coupon, usage limit is indeed reached.
		$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED;
	} elseif ( is_user_logged_in() ) {
		$recent_pending_orders = wc_get_orders(
			array(
				'limit'       => 1,
				'post_status' => array( 'wc-failed', 'wc-pending' ),
				'customer'    => get_current_user_id(),
				'return'      => 'ids',
			)
		);
		if ( count( $recent_pending_orders ) > 0 ) {
			// User logged in and have a pending order, maybe they are trying to use the coupon.
			$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK;
		} else {
			$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED;
		}
	} else {
		// Maybe this user was trying to use the coupon but got stuck. We can't know for sure (performantly). Show a slightly better error message.
		$error_code = WC_Coupon::E_WC_COUPON_USAGE_LIMIT_COUPON_STUCK_GUEST;
	}
	throw new Exception( $coupon->get_coupon_error( $error_code ), $error_code );
}