generated from spatie/package-skeleton-laravel
-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathHasPrefixedId.php
64 lines (49 loc) · 1.68 KB
/
HasPrefixedId.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
<?php
namespace Spatie\PrefixedIds\Models\Concerns;
use Illuminate\Database\Eloquent\Model;
use Spatie\PrefixedIds\Exceptions\NoPrefixConfiguredForModel;
use Spatie\PrefixedIds\Exceptions\NoPrefixedModelFound;
use Spatie\PrefixedIds\PrefixedIds;
trait HasPrefixedId
{
public static function bootHasPrefixedId()
{
static::creating(function (Model $model) {
$attributeName = config('prefixed-ids.prefixed_id_attribute_name');
$model->{$attributeName} = $model->generatePrefixedId();
});
}
public function getPrefixedIdAttribute(): ?string
{
$attributeName = config('prefixed-ids.prefixed_id_attribute_name');
return $this->attributes[$attributeName] ?? null;
}
public static function findByPrefixedId(string $prefixedId): ?Model
{
$attributeName = config('prefixed-ids.prefixed_id_attribute_name');
return static::firstWhere($attributeName, $prefixedId);
}
public static function findByPrefixedIdOrFail(string $prefixedId): Model
{
if (is_null($model = static::findByPrefixedId($prefixedId))) {
throw NoPrefixedModelFound::make($prefixedId);
}
return $model;
}
protected function getIdPrefix(): string
{
$prefix = PrefixedIds::getPrefixForModel(static::class);
if (! $prefix) {
throw NoPrefixConfiguredForModel::make($this);
}
return $prefix;
}
protected function generatePrefixedId(): string
{
return "{$this->getIdPrefix()}{$this->getUniquePartForPrefixId()}";
}
protected function getUniquePartForPrefixId(): string
{
return PrefixedIds::getUniqueId();
}
}