-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUuidable.php
117 lines (97 loc) · 2.27 KB
/
Uuidable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace KDuma\Eloquent;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;
/**
* Class Uuidable.
*/
trait Uuidable
{
/**
* Boot the trait.
*/
protected static function bootUuidable()
{
static::creating(function (Model $model) {
$model->generateUuidOnCreateOrUpdate();
});
static::updating(function (Model $model) {
$model->generateUuidOnCreateOrUpdate();
});
}
/**
* Gets first model by uuid
*
* @return self
*/
public static function byUuid(string $uuid): self
{
return static::whereUuid($uuid)->first();
}
/**
* @throws \Exception
*/
public function regenerateUuid()
{
$this->{$this->getUuidField()} = $this->uuidGenerate();
}
/**
* Get the UUID field name associated with the model.
*
* @return string
*/
public function getUuidField()
{
if (!isset($this->uuid_field))
return 'uuid';
return $this->uuid_field;
}
/**
* @param $query
* @param $guid
* @return mixed
*/
public function scopeWhereUuid($query, $guid)
{
return $query->where($this->getTable().'.'.$this->getUuidField(), $guid);
}
/**
* @return string
* @throws \Exception
*/
protected function uuidGenerate()
{
$uuid = Uuid::uuid4()->toString();
if (!isset($this->check_for_uuid_duplicates) || !$this->check_for_uuid_duplicates)
return $uuid;
$rowCount = DB::table($this->getTable())->where($this->getUuidField(), $uuid)->count();
return $rowCount > 0 ? $this->uuidGenerate() : $uuid;
}
/**
* @throws \Exception
*/
protected function generateUuidOnCreateOrUpdate()
{
if($this->{$this->getUuidField()} == null)
$this->regenerateUuid();
}
/**
* @deprecated
* @param $query
* @param $guid
* @return mixed
*/
public function scopeWhereGuid($query, $guid)
{
return $this->scopeWhereUuid($query, $guid);
}
/**
* @deprecated
* @throws \Exception
*/
public function newGuid()
{
$this->regenerateUuid();
}
}