Completed
Push — master ( bebea9...1a6984 )
by Benjamin
08:23
created

UuidService   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 52
c 0
b 0
f 0
wmc 8
lcom 1
cbo 3
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 4 1
A getDefaultNamespace() 0 20 3
A validate() 0 4 1
A hash() 0 4 1
A strToHex() 0 8 2
1
<?php
2
3
namespace Bdelespierre\HasUuid;
4
5
use Bdelespierre\HasUuid\Contracts\UuidGenerator;
6
use Bdelespierre\HasUuid\Contracts\UuidValidator;
7
use Illuminate\Support\Facades\Config;
8
use Illuminate\Support\Str;
9
use Webpatser\Uuid\Uuid;
10
11
class UuidService implements UuidGenerator, UuidValidator
12
{
13
    /**
14
     * @var string
15
     */
16
    public static $defaultNamespace;
17
18
    public function generate(int $version, ?string $node = null, ?string $namespace = null): string
19
    {
20
        return Uuid::generate($version, $node, $namespace);
21
    }
22
23
    public static function getDefaultNamespace(): string
24
    {
25
        if (static::$defaultNamespace) {
26
            return static::$defaultNamespace;
27
        }
28
29
        // when no explicit namespace is provided,
30
        // the namespace is calculated from the
31
        // app key.
32
        $key = Config::get('app.key');
33
34
        $key = Str::startsWith($key, 'base64:')
35
            ? self::hash($key)
36
            : self::strToHex($key);
37
38
        // Webpatser/UUID needs 16 bytes for namespace
39
        // which is *slightly* unsafe because Laravel
40
        // generates 32 bytes keys...
41
        return substr($key, 32);
42
    }
43
44
    public function validate(string $uuid): bool
45
    {
46
        return Uuid::validate($uuid);
47
    }
48
49
    protected static function hash(string $key): string
50
    {
51
        return bin2hex(base64_decode(Str::after($key, 'base64:')));
52
    }
53
54
    protected static function strToHex(string $string): string
55
    {
56
        for ($i = 0, $hex = ''; $i < strlen($string); $i++) {
57
            $hex .= substr('0' . dechex(ord($string[$i])), -2);
58
        }
59
60
        return strtoupper($hex);
61
    }
62
}
63