Debian Codegraph @

lib/3rdParty/composer/symfony/uid/UuidV1.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
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 <[email protected]>
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 = strtolower(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 substr($this->uid, -12);
42 }
43
44 public function toV6(): UuidV6
45 {
46 $uuid = $this->uid;
47
48 return new UuidV6(substr($uuid, 15, 3).substr($uuid, 9, 4).$uuid[0].'-'.substr($uuid, 1, 4).'-6'.substr($uuid, 5, 3).substr($uuid, 18, 6).substr($uuid, 24));
49 }
50
51 public function toV7(): UuidV7
52 {
53 return $this->toV6()->toV7();
54 }
55
56 public static function generate(?\DateTimeInterface $time = null, ?Uuid $node = null): string
57 {
58 $uuid = !$time || !$node ? uuid_create(static::TYPE) : parent::NIL;
59
60 if ($time) {
61 if ($node) {
62 // use clock_seq from the node
63 $seq = substr($node->uid, 19, 4);
64 } elseif (!$seq = self::$clockSeq ?? '') {
65 // generate a static random clock_seq to prevent any collisions with the real one
66 $seq = substr($uuid, 19, 4);
67
68 do {
69 self::$clockSeq = \sprintf('%04x', random_int(0, 0x3FFF) | 0x8000);
70 } while ($seq === self::$clockSeq);
71
72 $seq = self::$clockSeq;
73 }
74
75 $time = BinaryUtil::dateTimeToHex($time);
76 $uuid = substr($time, 8).'-'.substr($time, 4, 4).'-1'.substr($time, 1, 3).'-'.$seq.substr($uuid, 23);
77 }
78
79 if ($node) {
80 $uuid = substr($uuid, 0, 24).substr($node->uid, 24);
81 }
82
83 return $uuid;
84 }
85 }