function commerce_coupon_generate_coupon_code in Commerce Coupon 7.2
Same name and namespace in other branches
- 7 commerce_coupon.module \commerce_coupon_generate_coupon_code()
Generates a new unique coupon code.
Parameters
string $type: Coupon type.
int $length: Optional The length of the new code.
Return value
string The new coupon code.
2 calls to commerce_coupon_generate_coupon_code()
- commerce_coupon_form_attach_coupons_validate in ./
commerce_coupon.module - Form validate callback: validate a new coupon from the discount UI.
- commerce_coupon_form_submit in includes/
commerce_coupon.admin.inc - Form submit callback: submit coupon entity form.
File
- ./
commerce_coupon.module, line 730 - Provides coupon functionality for Drupal Commerce.
Code
function commerce_coupon_generate_coupon_code($type, $length = NULL) {
// We define the possible characters. No 'l','1', 'i' to prevent
// reconisation problems.
$characters = array(
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'J',
'K',
'L',
'M',
'N',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'j',
'k',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
);
$number_of_characters = count($characters);
$code_found = FALSE;
if ($length == NULL) {
$length = variable_get('commerce_coupon_' . $type . '_default_code_size', 8);
}
// We need to check if the produced coupon code is already in the
// database. We try this for 1000 iteration. If we then not found a
// a code, we stop. There must be an error in this case.
for ($i = 0; $i < 1000 && $code_found == FALSE; $i++) {
$code = '';
// Create the code per character.
for ($c = 0; $c < $length; $c++) {
$rand_index = mt_rand(0, $number_of_characters - 1);
$code .= $characters[$rand_index];
}
// Check in the database if the generated code is already defined.
if (commerce_coupon_code_exists($code) == FALSE) {
$code_found = TRUE;
}
}
return $code;
}