1 | <?php |
||
16 | trait GeneratesUuid |
||
17 | { |
||
18 | protected $uuidVersions = [ |
||
19 | 'uuid1', |
||
20 | 'uuid3', |
||
21 | 'uuid4', |
||
22 | 'uuid5', |
||
23 | ]; |
||
24 | |||
25 | /** |
||
26 | * Determine whether an attribute should be cast to a native type. |
||
27 | * |
||
28 | * @param string $key |
||
29 | * @param array|string|null $types |
||
30 | * @return bool |
||
31 | */ |
||
32 | abstract public function hasCast($key, $types = null); |
||
33 | |||
34 | /** |
||
35 | * Boot the trait, adding a creating observer. |
||
36 | * |
||
37 | * When persisting a new model instance, we resolve the UUID field, then set |
||
38 | * a fresh UUID, taking into account if we need to cast to binary or not. |
||
39 | */ |
||
40 | public static function bootGeneratesUuid() |
||
41 | { |
||
42 | 6 | static::creating(function ($model) { |
|
43 | 6 | $uuid = $model->resolveUuid(); |
|
44 | |||
45 | 6 | if (isset($model->attributes['uuid']) && ! is_null($model->attributes['uuid'])) { |
|
46 | 4 | $uuid = $uuid->fromString(strtolower($model->attributes['uuid'])); |
|
47 | 4 | } |
|
48 | |||
49 | 6 | $model->attributes['uuid'] = $model->hasCast('uuid') ? $uuid->getBytes() : $uuid->toString(); |
|
50 | 6 | }); |
|
51 | 2 | } |
|
52 | |||
53 | /** |
||
54 | * Resolve a UUID instance for the configured version. |
||
55 | * |
||
56 | * @return \Ramsey\Uuid\Uuid |
||
57 | */ |
||
58 | 6 | public function resolveUuid() |
|
62 | |||
63 | /** |
||
64 | * Resolve the UUID version to use when setting the UUID value. Default to uuid4. |
||
65 | * |
||
66 | * @return string |
||
67 | */ |
||
68 | 11 | public function resolveUuidVersion() |
|
76 | |||
77 | /** |
||
78 | * Scope queries to find by UUID. |
||
79 | * |
||
80 | * @param \Illuminate\Database\Eloquent\Builder $query |
||
81 | * @param string $uuid |
||
82 | * |
||
83 | * @return \Illuminate\Database\Eloquent\Builder |
||
84 | */ |
||
85 | 2 | public function scopeWhereUuid($query, $uuid) |
|
91 | |||
92 | /** |
||
93 | * Cast an attribute to a native PHP type. |
||
94 | * |
||
95 | * @param string $key |
||
96 | * @param mixed $value |
||
97 | * @return mixed |
||
98 | */ |
||
99 | 2 | protected function castAttribute($key, $value) |
|
107 | } |
||
108 |