<?php
class IdGenerator
{
const EPOCH = 1479533469598;
const max12bit = 4095;
const max41bit = 1099511627775;
const WAIT_TIME_MS = 1000;
static $machineId = null;
static $lastTimestamp = 0;
static $sequence = 0;
public static function machineId($mId = 0) {
self::$machineId = $mId;
}
public static function generateParticle() {
$time = floor(microtime(true) * 1000);
if ($time < self::$lastTimestamp) {
usleep((self::$lastTimestamp - $time + self::WAIT_TIME_MS) * 1000);
$time = floor(microtime(true) * 1000);
}
if ($time == self::$lastTimestamp) {
self::$sequence++;
if (self::$sequence > self::max12bit) {
$time = self::$lastTimestamp + 1;
while ($time <= self::$lastTimestamp) {
$time = floor(microtime(true) * 1000);
}
self::$sequence = 0;
}
} else {
self::$sequence = 0;
}
self::$lastTimestamp = $time;
$time -= self::EPOCH;
$base = decbin(self::max41bit + $time);
if (self::$machineId !== null) {
$machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
} else {
$machineid = str_pad(decbin(0), 10, "0", STR_PAD_LEFT);
}
$random = str_pad(decbin(self::$sequence), 12, "0", STR_PAD_LEFT);
$base = $base.$machineid.$random;
return bindec($base);
}
}
IdGenerator::machineId(1);
var_dump(IdGenerator::generateParticle());
IdGenerator::machineId(3);
for ($i = 0; $i <= 10; $i++) {
var_dump(IdGenerator::generateParticle());
}
?>