Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Generate a random string of non-ambiguous numbers and letters.
<?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;
}
}
<?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