PHP中的简单UUID v4生成器

1.3.3 2023-02-15 02:24 UTC

This package is auto-updated.

Last update: 2024-09-15 05:49:50 UTC


README

安装

composer require rafalswierczek/uuid4

使用方法

$uuid4 = Uuid4Factory::create();

$uuid4 = new Uuid4('f3d7fa06-d938-4c22-9505-c585efa381df');

$uuid4 = new Uuid4(Uuid4Factory::createBinary()->toHex());

$uuid4 = new Uuid4(Uuid4Factory::create()->toHex());

$uuid4Binary = Uuid4Factory::createBinary();

$uuid4Binary = new Uuid4Binary(random_bytes(16));

$uuid4Binary = new Uuid4Binary(Uuid4Factory::createBinary()->toBinary());

$uuid4Binary = new Uuid4Binary(Uuid4Factory::create()->toBinary());

// example 1:
$userClass = new class()
{
    private Uuid4Interface $uuid4;

    public function getUuid(bool $toHex = true): string
    {
        return $toHex ? $this->uuid4->toHex() : $this->uuid4->toBinary();
    }

    public function setUuid(Uuid4Interface $uuid4): void
    {
        $this->uuid4 = $uuid4;
    }
};

$userClass->setUuid(Uuid4Factory::createBinary());
$uuid4 = $userClass->getUuid(toHex: true); // hex format

// example 2:
$unknownSource = 'f3d7fa06-d938-4c22-9505-c585efaxxxxx';
Uuid4::validate($unknownSource);

// example 3:
$uuid4 = new Uuid4('f3d7fa06-d938-4c22-9505-c585efa381df'); // this also calls validate method because it is VO
$uuid4Binary = new Uuid4Binary($uuid4->toBinary());         // this also calls validate method because it is VO
$hexEqualsBin = $uuid4->equals($uuid4Binary);
$binEqualsHex = $uuid4Binary->equals($uuid4);

说明

UUID v4是128位随机数据(经过少量修改)以十六进制表示。

数据分为16个八位字节(从0到15),每个字节8位。

八位字节分组为以下名称的段落

  • time_low(字节0-3)
  • time_mid(字节4-5)
  • time_high_and_version(字节6-7)
  • clock_seq_and_reserved(字节8)
  • clock_seq_low(字节9)
  • node(字节10-15)

UUID4的结果以十六进制表示如下

f2e0aa63-22f2-410c-bcfa-9475cf573193

如你所见,例如time_low有4个字节,每个字节如下:以十六进制表示的f2e0aa63

现在一旦你有了128位随机数据,你必须在字节8上按以下方式进行修改:将最高两位(MSB)设置为:01。例如,假设第8个字节如下:01101101。现在你必须确保最左边的两位是00,然后你可以添加想要的10,结果就是:10101101。这就是如何做的

01101101 & 00111111 = 00101101

00101101 | 10000000 = 10101101

一旦更新了clock_seq_and_reserved,就到了修改字节6(time_high_and_version的第一个8位)的时候了。你必须执行相同的步骤,但使用00001111进行AND操作和01000000进行OR操作。例如,如果第6个字节是10100101,结果是01000101,所以前4位被替换为0100,这些位是UUID v4保留的位。

在修改了128位随机数据的字节8和6并将其转换为十六进制表示后,你就有了一个可以使用的UUID v4字符串:)

RFC: https://datatracker.ietf.org/doc/html/rfc4122#section-4.4