Passed
Push — master ( 722e10...89b581 )
by Julián
05:32
created

AbstractUuidIdentity::assertUuidVariant()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 3
nc 2
nop 1
1
<?php
2
3
/*
4
 * identity (https://github.com/phpgears/identity).
5
 * Identity objects for PHP.
6
 *
7
 * @license MIT
8
 * @link https://github.com/phpgears/identity
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Gears\Identity;
15
16
use Gears\Identity\Exception\InvalidIdentityException;
17
use Ramsey\Uuid\Exception\InvalidUuidStringException;
18
use Ramsey\Uuid\Uuid;
19
use Ramsey\Uuid\UuidInterface;
20
21
/**
22
 * Immutable UUID based identity.
23
 */
24
abstract class AbstractUuidIdentity extends AbstractIdentity
25
{
26
    /**
27
     * @param string $uuidString
28
     *
29
     * @throws InvalidUuidStringException
30
     *
31
     * @return UuidInterface
32
     */
33
    final protected static function uuidFromString(string $uuidString): UuidInterface
34
    {
35
        try {
36
            $uuid = Uuid::fromString($uuidString);
37
        } catch (InvalidUuidStringException $exception) {
38
            throw new InvalidIdentityException(
39
                \sprintf('Provided identity value "%s" is not a valid UUID', $uuidString),
40
                0,
41
                $exception
42
            );
43
        }
44
45
        static::assertUuidVariant($uuid);
46
47
        return $uuid;
48
    }
49
50
    /**
51
     * Assert correct UUID variant.
52
     *
53
     * @param UuidInterface $uuid
54
     *
55
     * @throws InvalidUuidStringException
56
     */
57
    final protected static function assertUuidVariant(UuidInterface $uuid): void
58
    {
59
        if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) {
60
            throw new InvalidIdentityException(
61
                \sprintf('Provided identity value "%s" is not a valid UUID', $uuid->toString())
62
            );
63
        }
64
    }
65
}
66