SnowflakeId.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace app\common\controller;
  3. class SnowflakeId
  4. {
  5. const EPOCH = 1479533469598;
  6. const max12bit = 4095;
  7. const max41bit = 1099511627775;
  8. static $machineId = null;
  9. public static function machineId($mId = 0) {
  10. self::$machineId = $mId;
  11. }
  12. public static function generateParticle() {
  13. /*
  14. * Time - 42 bits
  15. */
  16. $time = floor(microtime(true) * 1000);
  17. /*
  18. * Substract custom epoch from current time
  19. */
  20. $time -= self::EPOCH;
  21. /*
  22. * Create a base and add time to it
  23. */
  24. $base = decbin(self::max41bit + $time);
  25. /*
  26. * Configured machine id - 10 bits - up to 1024 machines
  27. */
  28. if(!self::$machineId) {
  29. $machineid = self::$machineId;
  30. } else {
  31. $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
  32. }
  33. /*
  34. * sequence number - 12 bits - up to 4096 random numbers per machine
  35. */
  36. $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);
  37. /*
  38. * Pack
  39. */
  40. $base = $base.$machineid.$random;
  41. /*
  42. * Return unique time id no
  43. */
  44. return bindec($base);
  45. }
  46. public static function timeFromParticle($particle) {
  47. /*
  48. * Return time
  49. */
  50. return bindec(substr(decbin($particle),0,41)) - self::max41bit + self::EPOCH;
  51. }
  52. }