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

UuidAsPrimary::getKeyType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
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