Completed
Push — master ( 0ab9be...347157 )
by Freek
01:33
created

HasSlug::ensureValidSlugOptions()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4888
c 0
b 0
f 0
cc 5
nc 4
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();
0 ignored issues
show
Bug introduced by
The method generateSlugOnUpdate() does not exist on Illuminate\Database\Eloquent\Model. Did you maybe mean update()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
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
        return Str::slug($this->getSlugSourceString(), $this->slugOptions->slugSeparator, $this->slugOptions->slugLanguage);
79
    }
80
81
    protected function hasCustomSlugBeenUsed(): bool
82
    {
83
        $slugField = $this->slugOptions->slugField;
84
85
        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...
86
    }
87
88
    protected function getSlugSourceString(): string
89
    {
90
        if (is_callable($this->slugOptions->generateSlugFrom)) {
91
            $slugSourceString = call_user_func($this->slugOptions->generateSlugFrom, $this);
92
93
            return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
94
        }
95
96
        $slugSourceString = collect($this->slugOptions->generateSlugFrom)
97
            ->map(function (string $fieldName) : string {
98
                return data_get($this, $fieldName, '');
99
            })
100
            ->implode($this->slugOptions->slugSeparator);
101
102
        return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
103
    }
104
105
    protected function makeSlugUnique(string $slug): string
106
    {
107
        $originalSlug = $slug;
108
        $i = 1;
109
110
        while ($this->otherRecordExistsWithSlug($slug) || $slug === '') {
111
            $slug = $originalSlug.$this->slugOptions->slugSeparator.$i++;
112
        }
113
114
        return $slug;
115
    }
116
117
    protected function otherRecordExistsWithSlug(string $slug): bool
118
    {
119
        $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...
120
121
        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...
122
            $key = $key ?? '0';
123
        }
124
125
        return (bool) static::where($this->slugOptions->slugField, $slug)
126
            ->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...
127
            ->withoutGlobalScopes()
128
            ->first();
129
    }
130
131
    protected function ensureValidSlugOptions()
132
    {
133
        if (is_array($this->slugOptions->generateSlugFrom) && ! count($this->slugOptions->generateSlugFrom)) {
134
            throw InvalidOption::missingFromField();
135
        }
136
137
        if (! strlen($this->slugOptions->slugField)) {
138
            throw InvalidOption::missingSlugField();
139
        }
140
141
        if ($this->slugOptions->maximumLength <= 0) {
142
            throw InvalidOption::invalidMaximumLength();
143
        }
144
    }
145
}
146