UuidV4::generate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Helper;
6
7
use Exception;
8
use function bin2hex;
9
use function chr;
10
use function ord;
11
use function random_bytes;
12
use function str_split;
13
14
class UuidV4
15
{
16
    /**
17
     * @see https://stackoverflow.com/a/15875555
18
     *
19
     * @return string
20
     * @throws Exception
21
     */
22
    public static function generate(): string
23
    {
24
        $string    = random_bytes(16);
25
        $string[6] = chr(ord($string[6]) & 0x0f | 0x40); // set version to 0100
26
        $string[8] = chr(ord($string[8]) & 0x3f | 0x80); // set bits 6-7 to 10
27
28
        $byteSlices = str_split(bin2hex($string), 4);
29
        assert(!is_bool($byteSlices));
30
31
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', $byteSlices);
32
    }
33
}
34