Completed
Push — master ( 106757...7f586e )
by Julián
08:01
created

ShortUuidIdentity::fromString()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
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 PascalDeVink\ShortUuid\ShortUuid;
18
use Ramsey\Uuid\Exception\InvalidUuidStringException;
19
use Ramsey\Uuid\Uuid;
20
21
/**
22
 * Short UUID identity.
23
 */
24
class ShortUuidIdentity extends AbstractIdentity
25
{
26
    /**
27
     * {@inheritdoc}
28
     *
29
     * @throws InvalidIdentityException
30
     */
31
    final public static function fromString(string $value)
32
    {
33
        $uuid = (new ShortUuid())->decode($value);
34
        if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) {
35
            throw new InvalidIdentityException(
36
                \sprintf('Provided identity value "%s" is not a valid short UUID', $value)
37
            );
38
        }
39
40
        return new static($value);
41
    }
42
43
    /**
44
     * Get identity from UUID string.
45
     *
46
     * @param string $value
47
     *
48
     * @return mixed|static
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use ShortUuidIdentity.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
49
     */
50
    final public static function fromUuid(string $value)
51
    {
52
        try {
53
            $uuid = Uuid::fromString($value);
54
        } catch (InvalidUuidStringException $exception) {
55
            throw new InvalidIdentityException(
56
                \sprintf('Provided identity value "%s" is not a valid UUID', $value),
57
                0,
58
                $exception
59
            );
60
        }
61
62
        if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) {
63
            throw new InvalidIdentityException(
64
                \sprintf('Provided identity value "%s" is not a valid UUID', $value)
65
            );
66
        }
67
68
        return new static((new ShortUuid())->encode($uuid));
69
    }
70
}
71