Completed
Pull Request — master (#122)
by
unknown
01:14
created

HasSlug   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 166
Duplicated Lines 3.61 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 31
lcom 1
cbo 4
dl 6
loc 166
rs 9.92
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
getSlugOptions() 0 1 ?
A bootHasSlug() 0 10 1
A generateSlugOnCreate() 0 10 2
A generateSlugOnUpdate() 0 10 2
A generateSlug() 0 6 1
A addSlug() 0 14 2
B generateNonUniqueSlug() 6 24 7
A hasCustomSlugBeenUsed() 0 6 1
A getSlugSourceString() 0 16 2
A makeSlugUnique() 0 11 3
A otherRecordExistsWithSlug() 0 18 3
A usesSoftDeletes() 0 8 2
A ensureValidSlugOptions() 0 14 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Spatie\Sluggable;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Database\Eloquent\Model;
7
8
trait HasSlug
9
{
10
    /** @var \Spatie\Sluggable\SlugOptions */
11
    protected $slugOptions;
12
13
    abstract public function getSlugOptions(): SlugOptions;
14
15
    protected static function bootHasSlug()
16
    {
17
        static::creating(function (Model $model) {
18
            $model->generateSlugOnCreate();
19
        });
20
21
        static::updating(function (Model $model) {
22
            $model->generateSlugOnUpdate();
23
        });
24
    }
25
26
    protected function generateSlugOnCreate()
27
    {
28
        $this->slugOptions = $this->getSlugOptions();
29
30
        if (! $this->slugOptions->generateSlugsOnCreate) {
31
            return;
32
        }
33
34
        $this->addSlug();
35
    }
36
37
    protected function generateSlugOnUpdate()
38
    {
39
        $this->slugOptions = $this->getSlugOptions();
40
41
        if (! $this->slugOptions->generateSlugsOnUpdate) {
42
            return;
43
        }
44
45
        $this->addSlug();
46
    }
47
48
    public function generateSlug()
49
    {
50
        $this->slugOptions = $this->getSlugOptions();
51
52
        $this->addSlug();
53
    }
54
55
    protected function addSlug()
56
    {
57
        $this->ensureValidSlugOptions();
58
59
        $slug = $this->generateNonUniqueSlug();
60
61
        if ($this->slugOptions->generateUniqueSlugs) {
62
            $slug = $this->makeSlugUnique($slug);
63
        }
64
65
        $slugField = $this->slugOptions->slugField;
66
67
        $this->$slugField = $slug;
68
    }
69
70
    protected function generateNonUniqueSlug(): string
71
    {
72
        $slugField = $this->slugOptions->slugField;
73
74
        if ($this->hasCustomSlugBeenUsed() && ! empty($this->$slugField)) {
75
            return $this->$slugField;
76
        }
77
78
        $slugSourceString = $this->getSlugSourceString();
79
80
        if (!empty($this->slugOptions->prefixSlug) || !empty($this->slugOptions->suffixSlug)) {
81
82 View Code Duplication
            if (!empty($this->slugOptions->prefixSlug)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
83
                $slugSourceString  = $this->slugOptions->prefixSlug . $this->slugOptions->slugSeparator . $slugSourceString;
84
            }
85
86 View Code Duplication
            if (!empty($this->slugOptions->suffixSlug)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
87
                $slugSourceString  = $slugSourceString . $this->slugOptions->slugSeparator . $this->slugOptions->suffixSlug;
88
            }
89
90
        }
91
92
        return Str::slug($slugSourceString, $this->slugOptions->slugSeparator, $this->slugOptions->slugLanguage);
93
    }
94
95
    protected function hasCustomSlugBeenUsed(): bool
96
    {
97
        $slugField = $this->slugOptions->slugField;
98
99
        return $this->getOriginal($slugField) != $this->$slugField;
0 ignored issues
show
Bug introduced by
It seems like getOriginal() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
100
    }
101
102
    protected function getSlugSourceString(): string
103
    {
104
        if (is_callable($this->slugOptions->generateSlugFrom)) {
105
            $slugSourceString = call_user_func($this->slugOptions->generateSlugFrom, $this);
106
107
            return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
108
        }
109
110
        $slugSourceString = collect($this->slugOptions->generateSlugFrom)
111
            ->map(function (string $fieldName) : string {
112
                return data_get($this, $fieldName, '');
113
            })
114
            ->implode($this->slugOptions->slugSeparator);
115
116
        return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
117
    }
118
119
    protected function makeSlugUnique(string $slug): string
120
    {
121
        $originalSlug = $slug;
122
        $i = 1;
123
124
        while ($this->otherRecordExistsWithSlug($slug) || $slug === '') {
125
            $slug = $originalSlug.$this->slugOptions->slugSeparator.$i++;
126
        }
127
128
        return $slug;
129
    }
130
131
    protected function otherRecordExistsWithSlug(string $slug): bool
132
    {
133
        $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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
134
135
        if ($this->incrementing) {
0 ignored issues
show
Bug introduced by
The property incrementing does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
136
            $key = $key ?? '0';
137
        }
138
139
        $query = static::where($this->slugOptions->slugField, $slug)
140
            ->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?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
141
            ->withoutGlobalScopes();
142
143
        if ($this->usesSoftDeletes()) {
144
            $query->withTrashed();
145
        }
146
147
        return $query->exists();
148
    }
149
150
    protected function usesSoftDeletes()
151
    {
152
        if (in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($this))) {
153
            return true;
154
        }
155
156
        return false;
157
    }
158
159
    protected function ensureValidSlugOptions()
160
    {
161
        if (is_array($this->slugOptions->generateSlugFrom) && ! count($this->slugOptions->generateSlugFrom)) {
162
            throw InvalidOption::missingFromField();
163
        }
164
165
        if (! strlen($this->slugOptions->slugField)) {
166
            throw InvalidOption::missingSlugField();
167
        }
168
169
        if ($this->slugOptions->maximumLength <= 0) {
170
            throw InvalidOption::invalidMaximumLength();
171
        }
172
    }
173
}
174