function commerce_coupon_generate_coupon_code in Commerce Coupon 7
Same name and namespace in other branches
- 7.2 commerce_coupon.module \commerce_coupon_generate_coupon_code()
Generates a new unique coupon code.
Parameters
$length: Optional The length of the new code.
Return value
String The new coupon code.
1 call to commerce_coupon_generate_coupon_code()
- CommerceCouponEntityController::save in classes/
commerce_coupon.inc - Saves a coupon.
File
- ./
commerce_coupon.module, line 171 - Coupon System for Drupal Commerce.
Code
function commerce_coupon_generate_coupon_code($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',
);
$numberOfCharacters = count($characters);
$codeFound = FALSE;
if ($length == NULL) {
$length = variable_get('commerce_coupon_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 && $codeFound == FALSE; $i++) {
$code = '';
// Create the code per character
for ($c = 0; $c < $length; $c++) {
$randIndex = mt_rand(0, $numberOfCharacters - 1);
$code .= $characters[$randIndex];
}
// Check in the database if the generated code is already defined.
if (commerce_coupon_code_exists($code) == FALSE) {
$codeFound = TRUE;
}
}
return $code;
}