Completed
Push — master ( 1992c5...803738 )
by Emad
02:25
created

Uuids::scopeUuid()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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