You are here

public function CouponCodeGenerator::generateCodes in Commerce Core 8.2

Generates coupon codes.

Ensures uniqueness, which means that depending on the pattern, the number of generated codes might be smaller than requested. This can be mitigated by using a pattern with a prefix/suffix.

Parameters

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

int $quantity: The quantity.

Return value

string[] The generated coupon codes.

Overrides CouponCodeGeneratorInterface::generateCodes

File

modules/promotion/src/CouponCodeGenerator.php, line 38

Class

CouponCodeGenerator

Namespace

Drupal\commerce_promotion

Code

public function generateCodes(CouponCodePattern $pattern, $quantity = 1) {
  $character_set = $this
    ->getCharacterSet($pattern
    ->getType());
  $character_set_size = count($character_set);
  $length = $pattern
    ->getLength();
  $prefix = $pattern
    ->getPrefix();
  $suffix = $pattern
    ->getSuffix();

  // Generate twice the requested quantity, to improve chances of having
  // the needed quantity after removing non-unique/existing codes.
  $codes = [];
  for ($i = 0; $i < $quantity * 2; $i++) {
    $code = '';
    while (strlen($code) < $length) {
      $random_index = mt_rand(0, $character_set_size - 1);
      $code .= $character_set[$random_index];
    }
    $codes[] = $prefix . $code . $suffix;
  }
  $codes = array_unique($codes);

  // Remove codes which already exist in the database.
  $result = $this->connection
    ->select('commerce_promotion_coupon', 'c')
    ->fields('c', [
    'code',
  ])
    ->condition('code', $codes, 'IN')
    ->execute();
  $existing_codes = $result
    ->fetchCol();
  $codes = array_diff($codes, $existing_codes);
  return array_slice($codes, 0, $quantity);
}