Skip to content

Commit

Permalink
add generate random string
Browse files Browse the repository at this point in the history
  • Loading branch information
wellingguzman committed Jan 20, 2016
1 parent e2c49a6 commit d510d13
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
35 changes: 35 additions & 0 deletions api/core/Directus/Util/StringUtils.php
Expand Up @@ -28,4 +28,39 @@ public static function endsWith($haystack, $needle)
// search forward starting from end minus needle length characters
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}

/**
* Return the length of the given string.
*
* @param string $value
* @return int
*/
public static function length($value)
{
return mb_strlen($value);
}

/**
* Generate a "random" alpha-numeric string.
*
* From Laravel
* @param int $length
* @return string
*/
public static function random($length = 16)
{
if (function_exists('openssl_random_pseudo_bytes')) {
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = openssl_random_pseudo_bytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}

return $string;
}

$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
}
}
14 changes: 14 additions & 0 deletions tests/api/Util/StringUtilsTest.php
Expand Up @@ -17,4 +17,18 @@ public function testEndsWith()
$this->assertTrue(StringUtils::endsWith($string, 'marston'));
$this->assertFalse(StringUtils::endsWith($string, 'john'));
}

public function testLength()
{
$this->assertEquals(10, StringUtils::length('mr. falcon'));
}

public function testRandom()
{
$length = 10;
$this->assertEquals(10, strlen(StringUtils::random($length)));
$this->assertEquals(16, strlen(StringUtils::random()));
$this->assertInternalType('string', StringUtils::random());
$this->assertEquals(1, strlen(StringUtils::random(1)));
}
}

0 comments on commit d510d13

Please sign in to comment.