-
Notifications
You must be signed in to change notification settings - Fork 0
/
ID.php
142 lines (123 loc) · 2.47 KB
/
ID.php
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php
/*
* This file is part of the SnowFlake ID generator package.
*
* (c) Alexey Popov <alexey.popov@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SnowFlake;
class ID
{
use TimeTrait;
/**
* Node number.
*
* @var int
*/
private $node;
/**
* Date of ID creation.
*
* @var int
*/
private $time;
/**
* Snowflake step.
*
* @var int
*/
private $step;
/**
* Epoch timestamp.
*
* @var int
*/
private $epoch;
/**
* @var int
*/
private $id;
/**
* ID constructor.
*
* @param int $node Node number
* @param int $time Date of ID creation
* @param int $step Snowflake step
* @param int $epoch
*/
public function __construct(int $node, int $time, int $step, int $epoch)
{
$this->node = $node;
$this->time = $time;
$this->step = $step;
$this->epoch = $epoch;
$this->id = $this->generate();
}
/**
* Returns node number.
*
* @return int
*/
public function getNode(): int
{
return $this->node;
}
/**
* Returns ID creation time.
*
* @return \DateTime
*/
public function getTime(): \DateTime
{
return $this->time($this->time);
}
/**
* Returns snowflake step.
*
* @return int
*/
public function getStep(): int
{
return $this->step;
}
/**
* Returns epoch.
*
* @return \DateTime
*/
public function getEpoch(): \DateTime
{
return $this->time((int) floor($this->epoch / 1000));
}
/**
* @return int
*/
public function toInt(): int
{
return $this->id;
}
/**
* Returns base36-encoded ID.
*
* @return string
*/
public function toString(): string
{
return base_convert($this->id, 10, 36);
}
/**
* Returns generated ID.
*
* @return int
*/
protected function generate(): int
{
$timeOffset = $this->time - $this->epoch;
$timeBits = str_pad(decbin($timeOffset), 41, '0', STR_PAD_LEFT);
$nodeBits = str_pad(decbin($this->node), 10, '0', STR_PAD_LEFT);
$stepBits = str_pad(decbin($this->step), 12, '0', STR_PAD_LEFT);
return (int) bindec('0'.$timeBits.$nodeBits.$stepBits);
}
}