| 148 |
lars |
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 |
* A v1 UUID contains a 60-bit timestamp and 62 extra unique bits.
|
|
|
16 |
*
|
|
|
17 |
* @author Grégoire Pineau <lyrixx@lyrixx.info>
|
|
|
18 |
*/
|
|
|
19 |
class UuidV1 extends Uuid implements TimeBasedUidInterface
|
|
|
20 |
{
|
|
|
21 |
protected const TYPE = 1;
|
|
|
22 |
|
|
|
23 |
private static string $clockSeq;
|
|
|
24 |
|
|
|
25 |
public function __construct(string $uuid = null)
|
|
|
26 |
{
|
|
|
27 |
if (null === $uuid) {
|
|
|
28 |
$this->uid = uuid_create(static::TYPE);
|
|
|
29 |
} else {
|
|
|
30 |
parent::__construct($uuid, true);
|
|
|
31 |
}
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
public function getDateTime(): \DateTimeImmutable
|
|
|
35 |
{
|
|
|
36 |
return BinaryUtil::hexToDateTime('0'.substr($this->uid, 15, 3).substr($this->uid, 9, 4).substr($this->uid, 0, 8));
|
|
|
37 |
}
|
|
|
38 |
|
|
|
39 |
public function getNode(): string
|
|
|
40 |
{
|
|
|
41 |
return uuid_mac($this->uid);
|
|
|
42 |
}
|
|
|
43 |
|
|
|
44 |
public static function generate(\DateTimeInterface $time = null, Uuid $node = null): string
|
|
|
45 |
{
|
|
|
46 |
$uuid = !$time || !$node ? uuid_create(static::TYPE) : parent::NIL;
|
|
|
47 |
|
|
|
48 |
if ($time) {
|
|
|
49 |
if ($node) {
|
|
|
50 |
// use clock_seq from the node
|
|
|
51 |
$seq = substr($node->uid, 19, 4);
|
|
|
52 |
} elseif (!$seq = self::$clockSeq ?? '') {
|
|
|
53 |
// generate a static random clock_seq to prevent any collisions with the real one
|
|
|
54 |
$seq = substr($uuid, 19, 4);
|
|
|
55 |
|
|
|
56 |
do {
|
|
|
57 |
self::$clockSeq = sprintf('%04x', random_int(0, 0x3FFF) | 0x8000);
|
|
|
58 |
} while ($seq === self::$clockSeq);
|
|
|
59 |
|
|
|
60 |
$seq = self::$clockSeq;
|
|
|
61 |
}
|
|
|
62 |
|
|
|
63 |
$time = BinaryUtil::dateTimeToHex($time);
|
|
|
64 |
$uuid = substr($time, 8).'-'.substr($time, 4, 4).'-1'.substr($time, 1, 3).'-'.$seq.substr($uuid, 23);
|
|
|
65 |
}
|
|
|
66 |
|
|
|
67 |
if ($node) {
|
|
|
68 |
$uuid = substr($uuid, 0, 24).substr($node->uid, 24);
|
|
|
69 |
}
|
|
|
70 |
|
|
|
71 |
return $uuid;
|
|
|
72 |
}
|
|
|
73 |
}
|