/** * Generates a random string of a given type and length. * * * $str = Text::random(); // 8 character random string * * The following types are supported: * * alnum * : Upper and lower case a-z, 0-9 (default) * * alpha * : Upper and lower case a-z * * hexdec * : Hexadecimal characters a-f, 0-9 * * distinct * : Uppercase characters and numbers that cannot be confused * * You can also create a custom type by providing the "pool" of characters * as the type. * * @param string $type a type of pool, or a string of characters to use as the pool * @param integer $length length of string to return * @return string * @uses UTF8::split */ public static function random($type = null, $length = 8) { if ($type === null) { // Default is to generate an alphanumeric string $type = 'alnum'; } $utf8 = false; switch ($type) { case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'hexdec': $pool = '0123456789abcdef'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; case 'distinct': $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; break; default: $pool = (string) $type; $utf8 = !UTF8::isAscii($pool); break; } // Split the pool into an array of characters $pool = $utf8 === true ? UTF8::strSplit($pool, 1) : str_split($pool, 1); // Largest pool key $max = count($pool) - 1; $str = ''; for ($i = 0; $i < $length; $i++) { // Select a random character from the pool and add it to the string $str .= $pool[mt_rand(0, $max)]; } // Make sure alnum strings contain at least one letter and one digit if ($type === 'alnum' && $length > 1) { if (ctype_alpha($str)) { // Add a random digit $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57)); } elseif (ctype_digit($str)) { // Add a random letter $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90)); } } return $str; }
/** * Tests UTF8::strSplit * * @test * @dataProvider provider_strSplit */ public function test_strSplit($input, $split_length, $expected) { $this->assertSame($expected, UTF8::strSplit($input, $split_length)); }