UuidTrait   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 93.33%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 4
c 2
b 0
f 1
lcom 0
cbo 1
dl 0
loc 35
ccs 14
cts 15
cp 0.9333
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A bootUuidTrait() 0 6 1
A provideUuidKey() 0 15 3
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