You are here

public static function CouponGenerateForm::processBatch in Commerce Core 8.2

Processes the batch and generates the coupons.

Parameters

int $quantity: The number of coupons to generate.

string[] $coupon_values: The initial coupon entity values.

\Drupal\commerce_promotion\CouponCodePattern $pattern: The pattern.

array $context: The batch context information.

File

modules/promotion/src/Form/CouponGenerateForm.php, line 235

Class

CouponGenerateForm
Provides a form for bulk generating coupons.

Namespace

Drupal\commerce_promotion\Form

Code

public static function processBatch($quantity, array $coupon_values, CouponCodePattern $pattern, array &$context) {
  if (empty($context['sandbox'])) {
    $context['sandbox']['total_quantity'] = (int) $quantity;
    $context['sandbox']['created'] = 0;
    $context['results']['codes'] = [];
    $context['results']['total_quantity'] = $quantity;
  }
  $total_quantity = $context['sandbox']['total_quantity'];
  $created =& $context['sandbox']['created'];
  $remaining = $total_quantity - $created;
  $coupon_storage = \Drupal::entityTypeManager()
    ->getStorage('commerce_promotion_coupon');
  $limit = $remaining < self::BATCH_SIZE ? $remaining : self::BATCH_SIZE;
  $coupon_code_generator = \Drupal::service('commerce_promotion.coupon_code_generator');
  $codes = $coupon_code_generator
    ->generateCodes($pattern, $limit);
  if (!empty($codes)) {
    foreach ($codes as $code) {
      $coupon = $coupon_storage
        ->create([
        'code' => $code,
      ] + $coupon_values);
      $coupon
        ->save();
      $context['results']['codes'][] = $code;
      $created++;
    }
    $context['message'] = t('Creating coupon @created of @total_quantity', [
      '@created' => $created,
      '@total_quantity' => $total_quantity,
    ]);
    $context['finished'] = $created / $total_quantity;
  }
  else {
    $context['finished'] = 1;
  }
}