Passed
Push — master ( 8d0533...722e10 )
by Julián
02:20
created

CondensedUuidIdentity   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 22
c 1
b 0
f 0
dl 0
loc 56
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A fromUuid() 0 19 4
A fromString() 0 21 4
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
20
/**
21
 * Condensed UUID identity.
22
 */
23
class CondensedUuidIdentity extends AbstractIdentity
24
{
25
    /**
26
     * {@inheritdoc}
27
     *
28
     * @throws InvalidIdentityException
29
     */
30
    final public static function fromString(string $value)
31
    {
32
        $uuidString = \sprintf('%s%s-%s-%s-%s-%s%s%s', ...\str_split($value, 4));
33
34
        try {
35
            $uuid = Uuid::fromString($uuidString);
36
        } catch (InvalidUuidStringException $exception) {
37
            throw new InvalidIdentityException(
38
                \sprintf('Provided identity value "%s" is not a valid condensed UUID', $value),
39
                0,
40
                $exception
41
            );
42
        }
43
44
        if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) {
45
            throw new InvalidIdentityException(
46
                \sprintf('Provided identity value "%s" is not a valid condensed UUID', $value)
47
            );
48
        }
49
50
        return new static($value);
51
    }
52
53
    /**
54
     * Get identity from UUID string.
55
     *
56
     * @param string $value
57
     *
58
     * @return mixed|static
59
     */
60
    final public static function fromUuid(string $value)
61
    {
62
        try {
63
            $uuid = Uuid::fromString($value);
64
        } catch (InvalidUuidStringException $exception) {
65
            throw new InvalidIdentityException(
66
                \sprintf('Provided identity value "%s" is not a valid UUID', $value),
67
                0,
68
                $exception
69
            );
70
        }
71
72
        if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) {
73
            throw new InvalidIdentityException(
74
                \sprintf('Provided identity value "%s" is not a valid UUID', $value)
75
            );
76
        }
77
78
        return new static(\str_replace('-', '', $value));
79
    }
80
}
81