1 | <?php |
||||||
2 | |||||||
3 | namespace Ronmrcdo\Inventory\Traits; |
||||||
4 | |||||||
5 | use Illuminate\Support\Str; |
||||||
6 | use Illuminate\Database\Eloquent\Model; |
||||||
7 | |||||||
8 | trait Sluggable |
||||||
9 | { |
||||||
10 | /** |
||||||
11 | * Generate a slug on the model on boot |
||||||
12 | * |
||||||
13 | * @return void |
||||||
14 | */ |
||||||
15 | protected static function bootSluggable(): void |
||||||
16 | { |
||||||
17 | static::creating(function (Model $model) { |
||||||
18 | $model->createUniqueSlug(); |
||||||
19 | }); |
||||||
20 | |||||||
21 | static::updating(function (Model $model) { |
||||||
22 | $model->createUniqueSlug(); |
||||||
23 | }); |
||||||
24 | } |
||||||
25 | |||||||
26 | protected function createUniqueSlug(): void |
||||||
27 | { |
||||||
28 | $this->slug = $this->generateUniqueSlug(); |
||||||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||||||
29 | } |
||||||
30 | |||||||
31 | /** |
||||||
32 | * Generate the unique string slug from the $sluggable property |
||||||
33 | * in the model |
||||||
34 | * |
||||||
35 | * @return string |
||||||
36 | */ |
||||||
37 | protected function generateUniqueSlug(): string |
||||||
38 | { |
||||||
39 | $slug = Str::slug($this->attributes[$this->sluggable]); |
||||||
40 | $i = 1; |
||||||
41 | |||||||
42 | while($this->isSlugExists($slug) || $slug === '') { |
||||||
43 | $slug = $slug.'-'.$i++; |
||||||
44 | } |
||||||
45 | |||||||
46 | return $slug; |
||||||
47 | } |
||||||
48 | |||||||
49 | /** |
||||||
50 | * Assert if the slug exists |
||||||
51 | * |
||||||
52 | * @return bool |
||||||
53 | */ |
||||||
54 | protected function isSlugExists(string $slug): bool |
||||||
55 | { |
||||||
56 | $key = $this->getKey(); |
||||||
0 ignored issues
–
show
It seems like
getKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
57 | |||||||
58 | if ($this->incrementing) { |
||||||
59 | $key ?? '0'; |
||||||
60 | } |
||||||
61 | |||||||
62 | $query = static::where('slug', $slug) |
||||||
63 | ->where($this->getKeyName(), '!=', $key) |
||||||
0 ignored issues
–
show
It seems like
getKeyName() must be provided by classes using this trait. How about adding it as abstract method to this trait?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||||
64 | ->withoutGlobalScopes(); |
||||||
65 | |||||||
66 | return $query->exists(); |
||||||
67 | } |
||||||
68 | } |