Created
February 21, 2014 14:55
-
-
Save lmammino/9135633 to your computer and use it in GitHub Desktop.
UidGenerator Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace LMammino\Generator; | |
class Uid | |
{ | |
/** | |
* @var string | |
*/ | |
protected $salt; | |
/** | |
* @param string $salt | |
*/ | |
public function __construct($salt) | |
{ | |
$this->salt = $salt; | |
} | |
/** | |
* Generates an uid of the given length | |
* | |
* @param int $len | |
* @return string | |
*/ | |
public function generate($len=8) | |
{ | |
$hex = md5($this->salt . uniqid()); | |
$pack = pack('H*', $hex); | |
$tmp = base64_encode($pack); | |
$uid = preg_replace("#(*UTF8)[^A-Za-z0-9]#", "", $tmp); | |
$len = max(4, min(128, $len)); | |
while (strlen($uid) < $len) { | |
$uid .= $this->generate(22); | |
} | |
return substr($uid, 0, $len); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment