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