1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bdelespierre\HasUuid; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Support\Facades\Config; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
use Webpatser\Uuid\Uuid; |
9
|
|
|
|
10
|
|
|
trait HasUuid |
11
|
|
|
{ |
12
|
|
|
abstract public function setKeyType($type); |
13
|
|
|
|
14
|
|
|
abstract public function setIncrementing($value); |
15
|
|
|
|
16
|
|
|
abstract public function getAttribute($key); |
17
|
|
|
|
18
|
|
|
abstract public static function creating($callback); |
19
|
|
|
|
20
|
|
|
public function __construct(array $attributes = []) |
21
|
|
|
{ |
22
|
|
|
parent::__construct($attributes); |
23
|
|
|
|
24
|
|
|
$this->setKeyType('string'); |
25
|
|
|
$this->setIncrementing(false); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
protected static function bootHasUuid() |
29
|
|
|
{ |
30
|
|
|
static::creating(function (Model $model) { |
31
|
|
|
if (! $model->getAttribute($model->getKeyName())) { |
32
|
|
|
$model->setAttribute( |
33
|
|
|
$model->getKeyName(), |
34
|
|
|
$model->getUuid() |
35
|
|
|
); |
36
|
|
|
} |
37
|
|
|
}); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function resolveRouteBinding($value, $field = null) |
|
|
|
|
41
|
|
|
{ |
42
|
|
|
if (! is_string($value) || ! app('uuid.validator')->validate($value)) { |
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return parent::resolveRouteBinding($value); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getUuid(): string |
50
|
|
|
{ |
51
|
|
|
return (string) app('uuid.generator')->generate( |
52
|
|
|
$this->getUuidVersion(), |
53
|
|
|
$this->getUuidNode(), |
54
|
|
|
$this->getUuidNamespace() |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function getUuidVersion(): int |
59
|
|
|
{ |
60
|
|
|
return $this->uuidVersion ?? 4; |
|
|
|
|
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function getUuidNode(): ?string |
64
|
|
|
{ |
65
|
|
|
return $this->interpolate($this->uuidNode); |
|
|
|
|
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function getUuidNamespace(): ?string |
69
|
|
|
{ |
70
|
|
|
return $this->interpolate($this->uuidNamespace) |
|
|
|
|
71
|
|
|
?: app('uuid.generator')->getDefaultNamespace(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
protected function interpolate(?string $value): ?string |
75
|
|
|
{ |
76
|
|
|
if (Str::startsWith($value, ':')) { |
77
|
|
|
return $this->getAttribute(Str::after($value, ':')); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $value; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.