Skip to content

Instantly share code, notes, and snippets.

@ahmadmarafa
Created February 22, 2019 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadmarafa/524a1ffd30bac33b4e70cb0c087bf316 to your computer and use it in GitHub Desktop.
Save ahmadmarafa/524a1ffd30bac33b4e70cb0c087bf316 to your computer and use it in GitHub Desktop.
<?php
namespace Itx\Utilities ;
class Random
{
public static function guid()
{
return sprintf(
'%s-%04x-%04x-%04d-%s',
self::string(8),
mt_rand(0, 65535),
mt_rand(0, 65535),
self::digits(4) ,
self::string(12)
);
}
public static function string(int $length = 5)
{
$length = $length <= 0 ? 5 : $length;
return substr(
bin2hex( self::bytes( $length * 2 ) )
, 0 , $length) ;
}
public static function digits($length = 5)
{
$length = $length > 19 ? 19 : $length ;
$start = ("1".str_repeat("0" , $length - 1));
$end = str_repeat("9" , $length) ;
return mt_rand( (int) $start , (int) $end ) ;
}
public static function bytes($length = 5)
{
if(function_exists("openssl_random_pseudo_bytes"))
{
return openssl_random_pseudo_bytes($length);
}
return random_bytes($length) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment