Completed
Push — master ( f2f349...c6aa94 )
by Avtandil
02:59
created

UuidAsPrimary   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 45
ccs 0
cts 33
cp 0
rs 10
wmc 8
lcom 1
cbo 2

4 Methods

Rating   Name   Duplication   Size   Complexity  
A bootUuidAsPrimary() 0 13 3
A generateUuid() 0 18 3
A getIncrementing() 0 4 1
A getKeyType() 0 4 1
1
<?php
2
/*
3
 * This file is part of the Laravel Lodash package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
declare(strict_types=1);
11
12
namespace Longman\LaravelLodash\Eloquent;
13
14
use Ramsey\Uuid\Uuid;
15
16
/**
17
 * @mixin \Illuminate\Database\Eloquent\Model
18
 */
19
trait UuidAsPrimary
20
{
21
    protected static function bootUuidAsPrimary()
22
    {
23
        /** @var \Illuminate\Database\Eloquent\Model $model */
24
        static::creating(function ($model) {
25
            $key_name = $model->getKeyName();
26
27
            if (empty($model->{$key_name})) {
28
                $uuidVersion = ! empty($model->uuidVersion) ? $model->uuidVersion : 4;
29
30
                $model->attributes[$key_name] = self::getUuid($uuidVersion);
31
            }
32
        });
33
    }
34
35
    public static function generateUuid(int $version = 4): string
36
    {
37
        switch ($version) {
38
            default:
39
                $uuid = Uuid::uuid4()->toString();
40
                break;
41
42
            case 1:
43
                $uuid = Uuid::uuid1()->toString();
44
                break;
45
46
            case 3:
47
                $uuid = Uuid::uuid3()->toString();
48
                break;
49
        }
50
51
        return $uuid;
52
    }
53
54
    public function getIncrementing(): bool
55
    {
56
        return false;
57
    }
58
59
    public function getKeyType(): string
60
    {
61
        return 'string';
62
    }
63
}
64