Completed
Push — master ( 709dbe...1b8636 )
by Freek
01:58
created

HasSlug   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 127
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3
Metric Value
wmc 15
lcom 1
cbo 3
dl 0
loc 127
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
getSlugOptions() 0 1 ?
A bootHasSlug() 0 10 1
A addSlug() 0 16 2
A generateNonUniqueSlug() 0 10 2
A hasCustomSlugBeenUsed() 0 6 1
A getSlugSourceString() 0 10 1
A makeSlugUnique() 0 11 3
A otherRecordExistsWithSlug() 0 6 1
A guardAgainstInvalidSlugOptions() 0 14 4
1
<?php
2
3
namespace Spatie\Sluggable;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
trait HasSlug
8
{
9
    /**
10
     * @var \Spatie\Sluggable\SlugOptions
11
     */
12
    protected $slugOptions;
13
14
    /**
15
     * Get the options for generating the slug.
16
     */
17
    abstract public function getSlugOptions() : SlugOptions;
18
19
    /**
20
     * Boot the trait.
21
     */
22
    protected static function bootHasSlug()
23
    {
24
        static::creating(function (Model $model) {
25
            $model->addSlug();
26
        });
27
28
        static::updating(function (Model $model) {
29
            $model->addSlug();
30
        });
31
    }
32
33
    /**
34
     * Add the slug to the model.
35
     */
36
    protected function addSlug()
37
    {
38
        $this->slugOptions = $this->getSlugOptions();
39
40
        $this->guardAgainstInvalidSlugOptions();
41
42
        $slug = $this->generateNonUniqueSlug();
43
44
        if ($this->slugOptions->generateUniqueSlugs) {
45
            $slug = $this->makeSlugUnique($slug);
46
        }
47
48
        $slugField = $this->slugOptions->slugField;
49
50
        $this->$slugField = $slug;
51
    }
52
53
    /**
54
     * Generate a non unique slug for this record.
55
     */
56
    protected function generateNonUniqueSlug() :  string
57
    {
58
        if ($this->hasCustomSlugBeenUsed()) {
59
            $slugField = $this->slugOptions->slugField;
60
61
            return $this->$slugField;
62
        }
63
64
        return str_slug($this->getSlugSourceString());
65
    }
66
67
    /**
68
     * Determine if a custom slug has been saved.
69
     */
70
    protected function hasCustomSlugBeenUsed() : bool
71
    {
72
        $slugField = $this->slugOptions->slugField;
73
74
        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...
75
    }
76
77
    /**
78
     * Get the string that should be used as base for the slug.
79
     */
80
    protected function getSlugSourceString() : string
81
    {
82
        $slugSourceString = collect($this->slugOptions->generateSlugFrom)
83
            ->map(function (string $fieldName) : string {
84
                return $this->$fieldName ?? '';
85
            })
86
            ->implode('-');
87
88
        return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
89
    }
90
91
    /**
92
     * Make the given slug unique.
93
     */
94
    protected function makeSlugUnique(string $slug) : string
95
    {
96
        $originalSlug = $slug;
97
        $i = 1;
98
99
        while ($this->otherRecordExistsWithSlug($slug) || $slug === '') {
100
            $slug = $originalSlug.'-'.$i++;
101
        }
102
103
        return $slug;
104
    }
105
106
    /**
107
     * Determine if a record exists with the given slug.
108
     */
109
    protected function otherRecordExistsWithSlug(string $slug) : bool
110
    {
111
        return (bool) static::where($this->slugOptions->slugField, $slug)
112
            ->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...
113
            ->first();
114
    }
115
116
    /**
117
     * This function will throw an exception when any of the options is missing or invalid.
118
     */
119
    protected function guardAgainstInvalidSlugOptions()
120
    {
121
        if (!count($this->slugOptions->generateSlugFrom)) {
122
            throw InvalidOption::missingFromField();
123
        }
124
125
        if (!strlen($this->slugOptions->slugField)) {
126
            throw InvalidOption::missingSlugField();
127
        }
128
129
        if ($this->slugOptions->maximumLength <= 0) {
130
            throw InvalidOption::invalidMaximumLength();
131
        }
132
    }
133
}
134