IdGenerator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Snowflake;
  12. abstract class IdGenerator implements IdGeneratorInterface
  13. {
  14. protected ConfigurationInterface $config;
  15. public function __construct(protected MetaGeneratorInterface $metaGenerator)
  16. {
  17. $this->config = $metaGenerator->getConfiguration();
  18. }
  19. public function generate(?Meta $meta = null): int
  20. {
  21. $meta = $this->meta($meta);
  22. $interval = $meta->getTimeInterval() << $this->config->getTimestampLeftShift();
  23. $dataCenterId = $meta->getDataCenterId() << $this->config->getDataCenterIdShift();
  24. $workerId = $meta->getWorkerId() << $this->config->getWorkerIdShift();
  25. return $interval | $dataCenterId | $workerId | $meta->getSequence();
  26. }
  27. public function degenerate(int $id): Meta
  28. {
  29. $interval = $id >> $this->config->getTimestampLeftShift();
  30. $dataCenterId = $id >> $this->config->getDataCenterIdShift();
  31. $workerId = $id >> $this->config->getWorkerIdShift();
  32. return new Meta(
  33. $interval << $this->config->getDataCenterIdBits() ^ $dataCenterId,
  34. $dataCenterId << $this->config->getWorkerIdBits() ^ $workerId,
  35. $workerId << $this->config->getSequenceBits() ^ $id,
  36. $interval + $this->metaGenerator->getBeginTimestamp(),
  37. $this->metaGenerator->getBeginTimestamp()
  38. );
  39. }
  40. public function getMetaGenerator(): MetaGeneratorInterface
  41. {
  42. return $this->metaGenerator;
  43. }
  44. protected function meta(?Meta $meta = null): Meta
  45. {
  46. if (is_null($meta)) {
  47. return $this->metaGenerator->generate();
  48. }
  49. return $meta;
  50. }
  51. }