Skip to content

Commit aceaa86

Browse files
Added Class
1 parent 6c06b9e commit aceaa86

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/ulid.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
namespace lewiscowles\core;
4+
5+
final class Ulid {
6+
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
7+
const ENCODING_LENGTH = 32;
8+
9+
public function get()
10+
{
11+
return $this->encodeTime($this->getTime(), 10) . $this->encodeRandom(16);
12+
}
13+
14+
private function encodeTime(int $time, int $length) : string
15+
{
16+
$out = '';
17+
while($length > 0) {
18+
$mod = intval($time % self::ENCODING_LENGTH);
19+
20+
$out = self::ENCODING[$mod] . $out;
21+
$time = ($time - $mod) / self::ENCODING_LENGTH;
22+
$length--;
23+
}
24+
return $out;
25+
}
26+
27+
private function encodeRandom(int $length) : string
28+
{
29+
$out = '';
30+
while($length > 0) {
31+
$rand = intval(floor(self::ENCODING_LENGTH * $this->getRand()));
32+
$out = self::ENCODING[$rand] . $out;
33+
$length--;
34+
}
35+
return $out;
36+
}
37+
38+
private function getRand() : float
39+
{
40+
return lcg_value();
41+
}
42+
43+
private function getTime() : int
44+
{
45+
return time();
46+
}
47+
}

0 commit comments

Comments
 (0)