Passed
Pull Request — master (#1119)
by Tarmo
08:41
created

UuidHelper::getFactory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Rest/UuidHelper.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\Rest;
10
11
use Ramsey\Uuid\Codec\OrderedTimeCodec;
12
use Ramsey\Uuid\Doctrine\UuidBinaryOrderedTimeType;
13
use Ramsey\Uuid\Doctrine\UuidBinaryType;
14
use Ramsey\Uuid\Exception\InvalidUuidStringException;
15
use Ramsey\Uuid\Rfc4122\FieldsInterface;
16
use Ramsey\Uuid\Uuid;
17
use Ramsey\Uuid\UuidFactory;
18
use Ramsey\Uuid\UuidInterface;
19
20
/**
21
 * Class UuidHelper
22
 *
23
 * @package App\Rest
24
 * @author TLe, Tarmo Leppänen <[email protected]>
25
 */
26
class UuidHelper
27
{
28
    private static ?UuidFactory $cache = null;
29
30
    /**
31
     * Getter method for UUID factory.
32
     */
33 861
    public static function getFactory(): UuidFactory
34
    {
35 861
        return self::$cache ??= self::initCache();
36
    }
37
38
    /**
39
     * Method to get proper doctrine parameter type for
40
     * UuidBinaryOrderedTimeType values.
41
     */
42 131
    public static function getType(string $value): ?string
43
    {
44 131
        $factory = self::getFactory();
45 131
        $output = null;
46
47
        try {
48 131
            $fields = $factory->fromString($value)->getFields();
49
50 87
            if ($fields instanceof FieldsInterface) {
51 87
                $output = $fields->getVersion() === 1 ? UuidBinaryOrderedTimeType::NAME : UuidBinaryType::NAME;
52
            }
53 44
        } catch (InvalidUuidStringException) {
54
            // ok, so now we know that value isn't uuid
55
        }
56
57 131
        return $output;
58
    }
59
60
    /**
61
     * Creates a UUID from the string standard representation
62
     */
63 215
    public static function fromString(string $value): UuidInterface
64
    {
65 215
        return self::getFactory()->fromString($value);
66
    }
67
68
    /**
69
     * Method to get bytes value for specified UuidBinaryOrderedTimeType value.
70
     */
71 4
    public static function getBytes(string $value): string
72
    {
73 4
        return self::fromString($value)->getBytes();
74
    }
75
76
    /**
77
     * Method to init UUID factory cache.
78
     *
79
     * @codeCoverageIgnore
80
     */
81
    private static function initCache(): UuidFactory
82
    {
83
        /** @var UuidFactory $factory */
84
        $factory = clone Uuid::getFactory();
85
        $codec = new OrderedTimeCodec($factory->getUuidBuilder());
86
        $factory->setCodec($codec);
87
88
        return $factory;
89
    }
90
}
91