Generate a random string of non-ambiguous numbers and letters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CodeGenerator | |
{ | |
private static $alphabet = '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; | |
private static $max_offset = 55; | |
/** | |
* Generate a random character of non-ambiguous number or letter. | |
* @return string the character | |
*/ | |
public static function randomChar() | |
{ | |
$index = mt_rand(0, self::$max_offset); | |
return self::$alphabet[$index]; | |
} | |
/** | |
* Generate a random string of non-ambiguous numbers and letters. | |
* @param $length Size of generated string | |
* @return string | |
* @throws InvalidArgumentException | |
*/ | |
public static function generate($length = 16) | |
{ | |
if ($length < 1) { | |
throw new InvalidArgumentException(__METHOD__ . ' expects a $length argument of at least 1, input was: ' . $length); | |
} | |
$random = ''; | |
for ($i=0; $i < $length; $i++) { | |
$random .= self::randomChar(); | |
} | |
return $random; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CodeGeneratorTest extends PHPUnit_Framework_TestCase | |
{ | |
public function testRandomCode() | |
{ | |
foreach (array(1, 10, 100) as $length) { | |
$random = CodeGenerator::generate($length); | |
$this->assertEquals($length, strlen($random)); | |
} | |
} | |
public function testZeroException() | |
{ | |
$this->setExpectedException('InvalidArgumentException'); | |
CodeGenerator::generate(0); | |
} | |
public function testNegativeException() | |
{ | |
$this->setExpectedException('InvalidArgumentException'); | |
CodeGenerator::generate(-1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment