Completed
Push — master ( 2ce091...c65964 )
by Freek
03:23 queued 02:19
created

HasSlug::guardAgainstInvalidSlugOptions()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 7
nc 4
nop 0
1
<?php
2
3
namespace Spatie\Sluggable;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
trait HasSlug
8
{
9
    /** @var \Spatie\Sluggable\SlugOptions */
10
    protected $slugOptions;
11
12
    /**
13
     * Get the options for generating the slug.
14
     */
15
    abstract public function getSlugOptions(): SlugOptions;
16
17
    /**
18
     * Boot the trait.
19
     */
20
    protected static function bootHasSlug()
21
    {
22
        static::creating(function (Model $model) {
23
            $model->generateSlugOnCreate();
24
        });
25
26
        static::updating(function (Model $model) {
27
            $model->generateSlugOnUpdate();
28
        });
29
    }
30
31
    /**
32
     * Handle adding slug on model creation.
33
     */
34
    protected function generateSlugOnCreate()
35
    {
36
        $this->slugOptions = $this->getSlugOptions();
37
38
        if (! $this->slugOptions->generateSlugsOnCreate) {
39
            return;
40
        }
41
42
        $this->addSlug();
43
    }
44
45
    /**
46
     * Handle adding slug on model update.
47
     */
48
    protected function generateSlugOnUpdate()
49
    {
50
        $this->slugOptions = $this->getSlugOptions();
51
52
        if (! $this->slugOptions->generateSlugsOnUpdate) {
53
            return;
54
        }
55
56
        $this->addSlug();
57
    }
58
59
    /**
60
     * Handle setting slug on explicit request.
61
     */
62
    public function generateSlug()
63
    {
64
        $this->slugOptions = $this->getSlugOptions();
65
66
        $this->addSlug();
67
    }
68
69
    /**
70
     * Add the slug to the model.
71
     */
72
    protected function addSlug()
73
    {
74
        $this->guardAgainstInvalidSlugOptions();
75
76
        $slug = $this->generateNonUniqueSlug();
77
78
        if ($this->slugOptions->generateUniqueSlugs) {
79
            $slug = $this->makeSlugUnique($slug);
80
        }
81
82
        $slugField = $this->slugOptions->slugField;
83
84
        $this->$slugField = $slug;
85
    }
86
87
    /**
88
     * Generate a non unique slug for this record.
89
     */
90
    protected function generateNonUniqueSlug(): string
91
    {
92
        if ($this->hasCustomSlugBeenUsed()) {
93
            $slugField = $this->slugOptions->slugField;
94
95
            return $this->$slugField;
96
        }
97
98
        return str_slug($this->getSlugSourceString(), $this->slugOptions->slugSeparator);
99
    }
100
101
    /**
102
     * Determine if a custom slug has been saved.
103
     */
104
    protected function hasCustomSlugBeenUsed(): bool
105
    {
106
        $slugField = $this->slugOptions->slugField;
107
108
        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...
109
    }
110
111
    /**
112
     * Get the string that should be used as base for the slug.
113
     */
114
    protected function getSlugSourceString(): string
115
    {
116
        if (is_callable($this->slugOptions->generateSlugFrom)) {
117
            $slugSourceString = call_user_func($this->slugOptions->generateSlugFrom, $this);
118
119
            return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
120
        }
121
122
        $slugSourceString = collect($this->slugOptions->generateSlugFrom)
123
            ->map(function (string $fieldName) : string {
124
                return $this->$fieldName ?? '';
125
            })
126
            ->implode($this->slugOptions->slugSeparator);
127
128
        return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
129
    }
130
131
    /**
132
     * Make the given slug unique.
133
     */
134
    protected function makeSlugUnique(string $slug): string
135
    {
136
        $originalSlug = $slug;
137
        $i = 1;
138
139
        while ($this->otherRecordExistsWithSlug($slug) || $slug === '') {
140
            $slug = $originalSlug.$this->slugOptions->slugSeparator.$i++;
141
        }
142
143
        return $slug;
144
    }
145
146
    /**
147
     * Determine if a record exists with the given slug.
148
     */
149
    protected function otherRecordExistsWithSlug(string $slug): bool
150
    {
151
        return (bool) static::where($this->slugOptions->slugField, $slug)
152
            ->where($this->getKeyName(), '!=', $this->getKey() ?? '0')
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...
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...
153
            ->withoutGlobalScopes()
154
            ->first();
155
    }
156
157
    /**
158
     * This function will throw an exception when any of the options is missing or invalid.
159
     */
160
    protected function guardAgainstInvalidSlugOptions()
161
    {
162
        if (is_array($this->slugOptions->generateSlugFrom) && ! count($this->slugOptions->generateSlugFrom)) {
163
            throw InvalidOption::missingFromField();
164
        }
165
166
        if (! strlen($this->slugOptions->slugField)) {
167
            throw InvalidOption::missingSlugField();
168
        }
169
170
        if ($this->slugOptions->maximumLength <= 0) {
171
            throw InvalidOption::invalidMaximumLength();
172
        }
173
    }
174
}
175