Completed
Push — master ( 99bfd8...3aa847 )
by Emad
9s
created

Uuids::bootUuids()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 3
eloc 8
nc 1
nop 0
1
<?php
2
namespace Emadadly\LaravelUuid;
3
4
use Ramsey\Uuid\Uuid;
5
use Illuminate\Database\Eloquent\ModelNotFoundException;
6
7
trait Uuids
8
{
9
10
    /**
11
     * Boot function from laravel.
12
     */
13
    protected static function bootUuids()
14
    {
15
        static::creating(function ($model) {
16
            if (!$model->{config('uuid.default_uuid_column')}) {
17
                $model->{config('uuid.default_uuid_column')} = strtoupper(Uuid::uuid4()->toString());
18
            }
19
        });
20
        static::saving(function ($model) {
21
            $original_uuid = $model->getOriginal(config('uuid.default_uuid_column'));
22
            if ($original_uuid !== $model->{config('uuid.default_uuid_column')}) {
23
                $model->{config('uuid.default_uuid_column')} = $original_uuid;
24
            }
25
        });
26
    }
27
28
    /**
29
     * Scope  by uuid 
30
     * @param  string  uuid of the model.
31
     * 
32
    */
33
    public function scopeUuid($query, $uuid, $first = true)
34
    {
35
        $match = preg_match('/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/', $uuid);
36
37
        if (!is_string($uuid) || $match !== 1)
38
        {
39
            throw (new ModelNotFoundException)->setModel(get_class($this));
40
        }
41
    
42
        $results = $query->where(config('uuid.default_uuid_column'), $uuid);
43
    
44
        return $first ? $results->firstOrFail() : $results;
45
    }
46
47
}
48