Skip to content

Commit

Permalink
Add generate random string method
Browse files Browse the repository at this point in the history
  • Loading branch information
misantron committed Jan 26, 2015
1 parent 91fbf21 commit b1c9d04
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Helper/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,20 @@ public static function plural($number, $forms)
}
return $number%10==1&&$number%100!=11?$forms[0]:($number%10>=2&&$number%10<=4&&($number%100<10||$number%100>=20)?$forms[1]:$forms[2]);
}

/**
* @param int $length
* @return string
*/
public static function generateRandom($length = 10)
{
$randChars = array();
$alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$alphabetSize = strlen($alphabet);
while(--$length+1){
$randChars[] = $alphabet[mt_rand(0, $alphabetSize-1)];;
}
shuffle($randChars);
return implode('', $randChars);
}
}
13 changes: 13 additions & 0 deletions tests/Helper/StringHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Utility\Test\Helper;

use Utility\Helper\StringHelper;

class StringHelperTest extends \PHPUnit_Framework_TestCase
{
public function testCut()
Expand All @@ -13,4 +15,15 @@ public function testPlural()
{

}

public function testGenerateRandom()
{
$string = StringHelper::generateRandom();
$this->assertEquals(10, strlen($string));
$this->assertRegExp('/^[a-zA-Z0-9]{10}$/', $string);

$string = StringHelper::generateRandom(17);
$this->assertEquals(17, strlen($string));
$this->assertRegExp('/^[a-zA-Z0-9]{17}$/', $string);
}
}

0 comments on commit b1c9d04

Please sign in to comment.