AutoCreateUuid::bootAutoCreateUuid()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 3
nc 1
nop 0
1
<?php
2
3
namespace mindtwo\LaravelAutoCreateUuid;
4
5
use Illuminate\Support\Str;
6
use Ramsey\Uuid\Uuid;
7
8
trait AutoCreateUuid
9
{
10
    /**
11
     * Boot auto create uuid trait.
12
     */
13
    public static function bootAutoCreateUuid()
14
    {
15
        // Auto populate uuid column on model creation
16
        static::creating(function ($model) {
17
            if(empty($model->{$model->getUuidColumn()}) || !Uuid::isValid($model->{$model->getUuidColumn()})) {
18
                $model->{$model->getUuidColumn()} = Str::uuid()->toString();
19
            }
20
        });
21
    }
22
23
    /**
24
     * Get the column name for uuid attribute.
25
     *
26
     * @return string
27
     */
28
    public function getUuidColumn(): string
29
    {
30
        return ! empty($this->uuid_column) ? $this->uuid_column : 'uuid';
0 ignored issues
show
Bug introduced by
The property uuid_column does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
31
    }
32
}
33