UuidTrait::bootUuidTrait()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.0156

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 1.0156
1
<?php namespace Bosnadev\Database\Traits;
2
3
use Illuminate\Database\Eloquent\Model;
4
use Rhumsaa\Uuid\Uuid;
5
use RuntimeException;
6
7
/**
8
 * Class UuidTrait
9
 * @package Bosnadev\Database\src\Traits
10
 */
11
trait UuidTrait
12
{
13
    /**
14
     *  This method will override model's boot method
15
     *
16
     * @return void
17
     */
18
    protected static function bootUuidTrait()
19
    {
20 6
        static::creating(function (Model $model) {
21
            $model->provideUuidKey($model);
22 6
        });
23 6
    }
24
25
    /**
26
     * Provide a UUID
27
     *
28
     * @param $model
29
     */
30 6
    protected function provideUuidKey($model)
31
    {
32
        // provide a UUID only if increment is disabled
33 6
        if ($model->incrementing === false) {
34 3
            $key = $model->getKeyName();
35
36 3
            if (empty($model->$key)) {
37 3
                $model->$key = (string)Uuid::uuid4();
38 3
            }
39 3
        } else {
40 3
            throw new RuntimeException(
41 3
              sprintf('$incrementing must be false on class "%s" to support uuid', get_class($this))
42 3
            );
43
        }
44 3
    }
45
}
46