1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\BinaryUuid; |
4
|
|
|
|
5
|
|
|
use Ramsey\Uuid\Uuid; |
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
7
|
|
|
use Illuminate\Database\Eloquent\Builder; |
8
|
|
|
|
9
|
|
|
trait HasBinaryUuid |
10
|
|
|
{ |
11
|
|
|
protected static function bootHasBinaryUuid() |
12
|
|
|
{ |
13
|
|
|
static::creating(function (Model $model) { |
14
|
|
|
if ($model->{$model->getKeyName()}) { |
15
|
|
|
return; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
$model->{$model->getKeyName()} = static::encodeUuid(Uuid::uuid1()); |
|
|
|
|
19
|
|
|
}); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public static function scopeWithUuid(Builder $builder, $uuid): Builder |
23
|
|
|
{ |
24
|
|
|
if (is_array($uuid)) { |
25
|
|
|
return $builder->whereIn('uuid', array_map(function (string $modelUuid) { |
26
|
|
|
return static::encodeUuid($modelUuid); |
27
|
|
|
}, $uuid)); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return $builder->where('uuid', static::encodeUuid($uuid)); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public static function encodeUuid(string $uuid): string |
34
|
|
|
{ |
35
|
|
|
$uuid = str_replace('-', '', (string) $uuid); |
36
|
|
|
|
37
|
|
|
return |
38
|
|
|
substr(hex2bin($uuid), 6, 2) |
39
|
|
|
.substr(hex2bin($uuid), 4, 2) |
40
|
|
|
.substr(hex2bin($uuid), 0, 4) |
41
|
|
|
.substr(hex2bin($uuid), 8, 8); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public static function decodeUuid(string $binary): string |
45
|
|
|
{ |
46
|
|
|
$uuid = bin2hex( |
47
|
|
|
substr($binary, 4, 4) |
48
|
|
|
.substr($binary, 2, 2) |
49
|
|
|
.substr($binary, 0, 2) |
50
|
|
|
.substr($binary, 8, 8) |
51
|
|
|
); |
52
|
|
|
|
53
|
|
|
collect([8, 13, 18, 23])->each(function ($position) use (&$uuid) { |
54
|
|
|
$uuid = substr_replace($uuid, '-', $position, 0); |
55
|
|
|
}); |
56
|
|
|
|
57
|
|
|
return $uuid; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function getUuidTextAttribute(): string |
61
|
|
|
{ |
62
|
|
|
return static::decodeUuid($this->{$this->getKeyName()}); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function setUuidTextAttribute(string $uuid) |
66
|
|
|
{ |
67
|
|
|
$this->{$this->getKeyName()} = static::encodeUuid($uuid); |
|
|
|
|
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: