Sluggable   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 18
c 0
b 0
f 0
dl 0
loc 59
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A generateUniqueSlug() 0 10 3
A createUniqueSlug() 0 3 1
A bootSluggable() 0 8 1
A isSlugExists() 0 13 2
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
The property slug does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
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
Bug introduced by
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 ignore-call  annotation

56
		/** @scrutinizer ignore-call */ 
57
  $key = $this->getKey();
Loading history...
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
Bug introduced by
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 ignore-call  annotation

63
				->where($this->/** @scrutinizer ignore-call */ getKeyName(), '!=', $key)
Loading history...
64
				->withoutGlobalScopes();
65
66
		return $query->exists();
67
	}
68
}