Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Created August 1, 2012 04:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lavoiesl/3223665 to your computer and use it in GitHub Desktop.
Save lavoiesl/3223665 to your computer and use it in GitHub Desktop.
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