Passed
Pull Request — master (#595)
by Def
04:35 queued 02:18
created

UuidHelper::isValidUuid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Helper;
6
7
use Yiisoft\Db\Exception\InvalidArgumentException;
8
9
use function bin2hex;
10
use function hex2bin;
11
use function preg_match;
12
use function str_replace;
13
14
final class UuidHelper
15
{
16
    public static function toUuid(string $blobString)
17
    {
18
        if (self::isValidUuid($blobString)) {
19
            return $blobString;
20
        }
21
22
        if (strlen($blobString) === 16) {
23
            $hex = bin2hex($blobString);
24
        } elseif (strlen($blobString) === 32 && self::isValidHexUuid($blobString)) {
25
            $hex = $blobString;
26
        } else {
27
            throw new InvalidArgumentException('Length of source data is should be 16 or 32 bytes.');
28
        }
29
30
        return
31
            substr($hex, 0, 8) . '-' .
32
            substr($hex, 8, 4) . '-' .
33
            substr($hex, 12, 4) . '-' .
34
            substr($hex, 16, 4) . '-' .
35
            substr($hex, 20)
36
        ;
37
    }
38
39
    public static function isValidUuid(string $uuidString): bool
40
    {
41
        return (bool) preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $uuidString);
42
    }
43
44
    public static function isValidHexUuid(string $uuidString): bool
45
    {
46
        return (bool) preg_match('/^[0-9a-f]{32}$/i', $uuidString);
47
    }
48
49
    public static function uuidToBlob(string $uuidString): string
50
    {
51
        if (!self::isValidUuid($uuidString)) {
52
            throw new InvalidArgumentException('Incorrect UUID.');
53
        }
54
55
        return (string) hex2bin(str_replace('-', '', $uuidString));
56
    }
57
}
58