Completed
Pull Request — master (#18)
by Kyle
01:36
created

HasSlug::bootHasSlug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
nc 1
cc 1
eloc 5
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->generateSlugOnCreate) {
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->generateSlugOnUpdate) {
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());
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
            return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
119
        }
120
121
        $slugSourceString = collect($this->slugOptions->generateSlugFrom)
122
            ->map(function (string $fieldName) : string {
123
                return $this->$fieldName ?? '';
124
            })
125
            ->implode('-');
126
127
        return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
128
    }
129
130
    /**
131
     * Make the given slug unique.
132
     */
133
    protected function makeSlugUnique(string $slug): string
134
    {
135
        $originalSlug = $slug;
136
        $i = 1;
137
138
        while ($this->otherRecordExistsWithSlug($slug) || $slug === '') {
139
            $slug = $originalSlug.'-'.$i++;
140
        }
141
142
        return $slug;
143
    }
144
145
    /**
146
     * Determine if a record exists with the given slug.
147
     */
148
    protected function otherRecordExistsWithSlug(string $slug): bool
149
    {
150
        return (bool) static::where($this->slugOptions->slugField, $slug)
151
            ->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...
152
            ->first();
153
    }
154
155
    /**
156
     * This function will throw an exception when any of the options is missing or invalid.
157
     */
158
    protected function guardAgainstInvalidSlugOptions()
159
    {
160
        if (!count($this->slugOptions->generateSlugFrom)) {
161
            throw InvalidOption::missingFromField();
162
        }
163
164
        if (!strlen($this->slugOptions->slugField)) {
165
            throw InvalidOption::missingSlugField();
166
        }
167
168
        if ($this->slugOptions->maximumLength <= 0) {
169
            throw InvalidOption::invalidMaximumLength();
170
        }
171
    }
172
}
173