8000 [Uid] add support for Ulid · symfony/symfony@d75d018 · GitHub
[go: up one dir, main page]

Skip to content

Commit d75d018

Browse files
[Uid] add support for Ulid
1 parent d108f7b commit d75d018

File tree

4 files changed

+330
-0
lines changed

4 files changed

+330
-0
lines changed

src/Symfony/Component/Uid/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@ CHANGELOG
55
-----
66

77
* added support for UUID
8+
* added support for ULID
89
* added the component
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Tests\Component\Uid;
13+
14+
use PHPUnit\Framework\TestCase;
15+
use Symfony\Component\Uid\Ulid;
16+
17+
class UlidTest extends TestCase
18+
{
19+
/**
20+
* @group time-sensitive
21+
*/
22+
public function testGenerate()
23+
{
24+
$a = new Ulid();
25+
$b = new Ulid();
26+
27+
$this->assertSame(0, strncmp($a, $b, 20));
28+
$a = base_convert(strtr(substr($a, -6), 'ABCDEFGHJKMNPQRSTVWXYZ', 'abcdefghijklmnopqrstuv'), 32, 10);
29+
$b = base_convert(strtr(substr($b, -6), 'ABCDEFGHJKMNPQRSTVWXYZ', 'abcdefghijklmnopqrstuv'), 32, 10);
30+
$this->assertSame(1, $b - $a);
31+
}
32+
33+
public function testWithInvalidUlid()
34+
{
35+
$this->expectException(\InvalidArgumentException::class);
36+
$this->expectExceptionMessage('Invalid ULID: "this is not a ulid".');
37+
38+
new Ulid('this is not a ulid');
39+
}
40+
41+
public function testBinary()
42+
{
43+
$ulid = new Ulid('00000000000000000000000000');
44+
$this->assertSame("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", $ulid->toBinary());
45+
46+
$ulid = new Ulid('3zzzzzzzzzzzzzzzzzzzzzzzzz');
47+
$this->assertSame('7fffffffffffffffffffffffffffffff', bin2hex($ulid->toBinary()));
48+
49+
$this->assertTrue($ulid->equals(Ulid::fromBinary(hex2bin('7fffffffffffffffffffffffffffffff'))));
50+
}
51+
52+
/**
53+
* @group time-sensitive
54+
*/
55+
public function testGetTime()
56+
{
57+
$time = microtime(false);
58+
$ulid = new Ulid();
59+
$time = substr($time, 11).substr($time, 1, 4);
60+
61+
$this->assertSame((float) $time, $ulid->getTime());
62+
}
63+
64+
public function testIsValid()
65+
{
66+
$this->assertFalse(Ulid::isValid('not a ulid'));
67+
$this->assertTrue(Ulid::isValid('00000000000000000000000000'));
68+
}
69+
70+
public function testEquals()
71+
{
72+
$a = new Ulid();
73+
$b = new Ulid();
74+
75+
$this->assertTrue($a->equals($a));
76+
$this->assertFalse($a->equals($b));
77+
}
78+
79+
/**
80+
* @group time-sensitive
81+
*/
82+
public function testCompare()
83+
{
84+
$a = new Ulid();
85+
$b = new Ulid();
86+
87+
$this->assertSame(0, $a->compare($a));
88+
$this->assertLessThan(0, $a->compare($b));
89+
$this->assertGreaterThan(0, $b->compare($a));
90+
91+
usleep(1001);
92+
$c = new Ulid();
93+
94+
$this->assertLessThan(0, $b->compare($c));
95+
$this->assertGreaterThan(0, $c->compare($b));
96+
}
97+
}

src/Symfony/Component/Uid/Ulid.php

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Uid;
13+
14+
/**
15+
* @see https://github.com/ulid/spec
16+
*
17+
* @experimental in 5.1
18+
*
19+
* @author Nicolas Grekas <p@tchwork.com>
20+
*/
21+
class Ulid implements \JsonSerializable
22+
{
23+
private static $time = -1;
24+
private static $rand = [];
25+
26+
private $ulid;
27+
28+
public function __construct(string $ulid = null)
29+
{
30+
if (null === $ulid) {
31+
$this->ulid = self::generate();
32+
33+
return;
34+
}
35+
36+
if (!self::isValid($ulid)) {
37+
throw new \InvalidArgumentException(sprintf('Invalid ULID: "%s".', $ulid));
38+
}
39+
40+
$this->ulid = strtr($ulid, 'abcdefghjkmnpqrstvwxyz', 'ABCDEFGHJKMNPQRSTVWXYZ');
41+
}
42+
43+
public static function isValid(string $ulid): bool
44+
{
45+
if (26 !== \strlen($ulid)) {
46+
return false;
47+
}
48+
49+
if (26 !== strspn($ulid, '0123456789ABCDEFGHJKMNPQRSTVWXYZabcdefghjkmnpqrstvwxyz')) {
50+
return false;
51+
}
52+
53+
return $ulid[0] <= '7';
54+
}
55+
56+
public static function fromBinary(string $ulid): self
57+
{
58+
if (16 !== \strlen($ulid)) {
59+
throw new \InvalidArgumentException('Invalid binary ULID.');
60+
}
61+
62+
$ulid = bin2hex($ulid);
63+
$ulid = sprintf('%02s%04s%04s%04s%04s%04s%04s',
64+
base_convert(substr($ulid, 0, 2), 16, 32),
65+
base_convert(substr($ulid, 2, 5), 16, 32),
66+
base_convert(substr($ulid, 7, 5), 16, 32),
67+
base_convert(substr($ulid, 12, 5), 16, 32),
68+
base_convert(substr($ulid, 17, 5), 16, 32),
69+
base_convert(substr($ulid, 22, 5), 16, 32),
70+
base_convert(substr($ulid, 27, 5), 16, 32)
71+
);
72+
73+
return new self(strtr($ulid, 'abcdefghijklmnopqrstuv', 'ABCDEFGHJKMNPQRSTVWXYZ'));
74+
}
75+
76+
public function toBinary()
77+
{
78+
$ulid = strtr($this->ulid, 'ABCDEFGHJKMNPQRSTVWXYZ', 'abcdefghijklmnopqrstuv');
79+
80+
$ulid = sprintf('%02s%05s%05s%05s%05s%05s%05s',
81+
base_convert(substr($ulid, 0, 2), 32, 16),
82+
base_convert(substr($ulid, 2, 4), 32, 16),
83+
base_convert(substr($ulid, 6, 4), 32, 16),
84+
base_convert(substr($ulid, 10, 4), 32, 16),
85+
base_convert(substr($ulid, 14, 4), 32, 16),
86+
base_convert(substr($ulid, 18, 4), 32, 16),
87+
base_convert(substr($ulid, 22, 4), 32, 16)
88+
);
89+
90+
return hex2bin($ulid);
91+
}
92+
93+
public function equals(self $other): bool
94+
{
95+
return $this->ulid === $other->ulid;
96+
}
97+
98+
public function compare(self $other): int
99+
{
100+
return strcmp($this->ulid, $other->ulid);
101+
}
102+
103+
public function getTime(): float
104+
{
105+
$time = strtr(substr($this->ulid, 0, 10), 'ABCDEFGHJKMNPQRSTVWXYZ', 'abcdefghijklmnopqrstuv');
106+
107+
if (\PHP_INT_SIZE >= 8) {
108+
return hexdec(base_convert($time, 32, 16)) / 1000;
109+
}
110+
111+
$time = sprintf('%02s%05s%05s',
112+
base_convert(substr($time, 0, 2), 32, 16),
113+
base_convert(substr($time, 2, 4), 32, 16),
114+
base_convert(substr($time, 6, 4), 32, 16)
115+
);
116+
117+
return self::toDecimal(hex2bin($time)) / 1000;
118+
}
119+
120+
public function __toString(): string
121+
{
122+
return $this->ulid;
123+
}
124+
125+
public function jsonSerialize(): string
126+
{
127+
return $this->ulid;
128+
}
129+
130+
private static function generate(): string
131+
{
132+
$time = microtime(false);
133+
$time = substr($time, 11).substr($time, 2, 3);
134+
135+
if ($time !== self::$time) {
136+
$r = unpack('nr1/nr2/nr3/nr4/nr', random_bytes(10));
137+
$r['r1'] |= ($r['r'] <<= 4) & 0xF0000;
138+
$r['r2'] |= ($r['r'] <<= 4) & 0xF0000;
139+
$r['r3'] |= ($r['r'] <<= 4) & 0xF0000;
140+
$r['r4'] |= ($r['r'] <<= 4) & 0xF0000;
141+
unset($r['r']);
142+
self::$rand = array_values($r);
143+
self::$time = $time;
144+
} elseif ([0xFFFFF, 0xFFFFF, 0xFFFFF, 0xFFFFF] === self::$rand) {
145+
usleep(100);
146+
147+
return self::generate();
148+
} else {
149+
for ($i = 3; $i >= 0 && 0xFFFFF === self::$rand[$i]; --$i) {
150+
self::$rand[$i] = 0;
151+
}
152+
153+
++self::$rand[$i];
154+
}
155+
156+
if (\PHP_INT_SIZE >= 8) {
157+
$time = base_convert($time, 10, 32);
158+
} else {
159+
$time = bin2hex(self::toBytes($time));
160+
$time = sprintf('%s%04s%04s',
161+
base_convert(substr($time, 0, 2), 16, 32),
162+
base_convert(substr($time, 2, 5), 16, 32),
163+
base_convert(substr($time, 7, 5), 16, 32)
164+
);
165+
}
166+
167+
return strtr(sprintf('%010s%04s%04s%04s%04s',
168+
$time,
169+
base_convert(self::$rand[0], 10, 32),
170+
base_convert(self::$rand[1], 10, 32),
171+
base_convert(self::$rand[2], 10, 32),
172+
base_convert(self::$rand[3], 10, 32)
173+
), 'abcdefghijklmnopqrstuv', 'ABCDEFGHJKMNPQRSTVWXYZ');
174+
}
175+
176+
private static function toBytes(string $digits): string
177+
{
178+
$bytes = '';
179+
$len = \strlen($digits);
180+
181+
while ($len > $i = strspn($digits, '0')) {
182+
for ($j = 2, $r = 0; $i < $len; $i += $j, $j = 0) {
183+
do {
184+
$r *= 10;
185+
$d = (int) substr($digits, $i, ++$j);
186+
} while ($i + $j < $len && $r + $d < 256);
187+
188+
$j = \strlen((string) $d);
189+
$q = str_pad(($d += $r) >> 8, $j, '0', STR_PAD_LEFT);
190+
$digits = substr_replace($digits, $q, $i, $j);
191+
$r = $d % 256;
192+
}
193+
194+
$bytes .= \chr($r);
195+
}
196+
197+
return strrev($bytes);
198+
}
199+
200+
private static function toDecimal(string $bytes): string
201+
{
202+
$digits = '';
203+
$len = \strlen($bytes);
204+
205+
while ($len > $i = strspn($bytes, "\0")) {
206+
for ($r = 0; $i < $len; $i += $j) {
207+
$j = $d = 0;
208+
do {
209+
$r <<= 8;
210+
$d = ($d << 8) + \ord($bytes[$i + $j]);
211+
} while ($i + ++$j < $len && $r + $d < 10);
212+
213+
if (256 < $d) {
214+
$q = intdiv($d += $r, 10);
215+
$bytes[$i] = \chr($q >> 8);
216+
$bytes[1 + $i] = \chr($q & 0xFF);
217+
} else {
218+
$bytes[$i] = \chr(intdiv($d += $r, 10));
219+
}
220+
$r = $d % 10;
221+
}
222+
223+
$digits .= (string) $r;
224+
}
225+
226+
return strrev($digits);
227+
}
228+
}

src/Symfony/Component/Uid/composer.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@
1010
"name": "Grégoire Pineau",
1111
"email": "lyrixx@lyrixx.info"
1212
},
13+
{
14+
"name": "Nicolas Grekas",
15+
"email": "p@tchwork.com"
16+
},
1317
{
1418
"name": "Symfony Community",
1519
"homepage": "https://symfony.com/contributors"

0 commit comments

Comments
 (0)
0