12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
- namespace core\util;
- use Exception;
- class Snowflake
- {
-
- const START_EPOCH = 1609459200000;
-
- const SEQUENCE_BITS = 12;
- const MACHINE_ID_BITS = 0;
- const DATA_CENTER_ID_BITS = 0;
-
- const MAX_SEQUENCE = 4095;
- const MAX_MACHINE_ID = 31;
- const MAX_DATA_CENTER_ID = 31;
- private $data_center_id;
- private $machine_id;
- private $last_timestamp;
- private $sequence;
- public function __construct($data_center_id, $machine_id)
- {
- $this->last_timestamp = 0;
- $this->sequence = 0;
- }
-
- public function generateId()
- {
- $timestamp = $this->getTimestamp();
-
- if ($timestamp < $this->last_timestamp) {
- throw new Exception('Clock moved backwards.');
- }
-
- if ($timestamp == $this->last_timestamp) {
- $this->sequence = ($this->sequence + 1) & self::MAX_SEQUENCE;
-
- if ($this->sequence == 0) {
- $timestamp = $this->nextMillis($this->last_timestamp);
- }
- } else {
-
- $this->sequence = 0;
- }
- $this->last_timestamp = $timestamp;
- return (($timestamp - self::START_EPOCH) << (self::SEQUENCE_BITS))
- | $this->sequence;
- }
- private function getTimestamp()
- {
- return floor(microtime(true) * 1000);
- }
- private function nextMillis($last_timestamp)
- {
- $timestamp = $this->getTimestamp();
- while ($timestamp <= $last_timestamp) {
- $timestamp = $this->getTimestamp();
- }
- return $timestamp;
- }
- }
|