Completed
Push — master ( 492a3b...c9d7f6 )
by Freek
25s
created

HasSlug::generateSlug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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
    public function resolveRouteBinding($value)
56
    {
57
        if ($this->getSlugOptions()->routeBinding) {
58
            return $this->where($this->getRouteKeyName(), $value)
0 ignored issues
show
Bug introduced by
It seems like getRouteKeyName() 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...
Bug introduced by
It seems like where() 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...
59
                        ->orWhere($this->getSlugOptions()->slugField, $value)
60
                        ->first();
61
        }
62
63
        return parent::resolveRouteBinding($value);
64
    }
65
66
    protected function addSlug()
67
    {
68
        $this->ensureValidSlugOptions();
69
70
        $slug = $this->generateNonUniqueSlug();
71
72
        if ($this->slugOptions->generateUniqueSlugs) {
73
            $slug = $this->makeSlugUnique($slug);
74
        }
75
76
        $slugField = $this->slugOptions->slugField;
77
78
        $this->$slugField = $slug;
79
    }
80
81
    protected function generateNonUniqueSlug(): string
82
    {
83
        $slugField = $this->slugOptions->slugField;
84
85
        if ($this->hasCustomSlugBeenUsed() && ! empty($this->$slugField)) {
86
            return $this->$slugField;
87
        }
88
89
        return Str::slug($this->getSlugSourceString(), $this->slugOptions->slugSeparator, $this->slugOptions->slugLanguage);
90
    }
91
92
    protected function hasCustomSlugBeenUsed(): bool
93
    {
94
        $slugField = $this->slugOptions->slugField;
95
96
        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...
97
    }
98
99
    protected function getSlugSourceString(): string
100
    {
101
        if (is_callable($this->slugOptions->generateSlugFrom)) {
102
            $slugSourceString = call_user_func($this->slugOptions->generateSlugFrom, $this);
103
104
            return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
105
        }
106
107
        $slugSourceString = collect($this->slugOptions->generateSlugFrom)
108
            ->map(function (string $fieldName) : string {
109
                return data_get($this, $fieldName, '');
110
            })
111
            ->implode($this->slugOptions->slugSeparator);
112
113
        return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
114
    }
115
116
    protected function makeSlugUnique(string $slug): string
117
    {
118
        $originalSlug = $slug;
119
        $i = 1;
120
121
        while ($this->otherRecordExistsWithSlug($slug) || $slug === '') {
122
            $slug = $originalSlug.$this->slugOptions->slugSeparator.$i++;
123
        }
124
125
        return $slug;
126
    }
127
128
    protected function otherRecordExistsWithSlug(string $slug): bool
129
    {
130
        $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...
131
132
        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...
133
            $key = $key ?? '0';
134
        }
135
136
        $query = static::where($this->slugOptions->slugField, $slug)
137
            ->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...
138
            ->withoutGlobalScopes();
139
140
        if ($this->usesSoftDeletes()) {
141
            $query->withTrashed();
142
        }
143
144
        return $query->exists();
145
    }
146
147
    protected function usesSoftDeletes()
148
    {
149
        if (in_array('Illuminate\Database\Eloquent\SoftDeletes', class_uses($this))) {
150
            return true;
151
        }
152
153
        return false;
154
    }
155
156
    protected function ensureValidSlugOptions()
157
    {
158
        if (is_array($this->slugOptions->generateSlugFrom) && ! count($this->slugOptions->generateSlugFrom)) {
159
            throw InvalidOption::missingFromField();
160
        }
161
162
        if (! strlen($this->slugOptions->slugField)) {
163
            throw InvalidOption::missingSlugField();
164
        }
165
166
        if ($this->slugOptions->maximumLength <= 0) {
167
            throw InvalidOption::invalidMaximumLength();
168
        }
169
    }
170
}
171