HasUrl::validateUrlOptions()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
rs 9.4888
cc 5
nc 4
nop 0
1
<?php
2
3
namespace Neurony\Url\Traits;
4
5
use Exception;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Relations\MorphOne;
9
use Illuminate\Support\Facades\DB;
10
use Illuminate\Support\Str;
11
use Neurony\Url\Exceptions\UrlException;
12
use Neurony\Url\Models\Url;
13
use Neurony\Url\Options\SlugOptions;
14
use Neurony\Url\Options\UrlOptions;
15
16
trait HasUrl
17
{
18
    use HasSlug;
19
20
    /**
21
     * The container for all the options necessary for this trait.
22
     * Options can be viewed in the Neurony\Url\Options\UrlOptions file.
23
     *
24
     * @var UrlOptions
25
     */
26
    protected $urlOptions;
27
28
    /**
29
     * Flag to manually enable/disable the url generation only for the current request.
30
     *
31
     * @var bool
32
     */
33
    protected static $generateUrl = true;
34
35
    /**
36
     * Set the options for the HasUrl trait.
37
     *
38
     * @return UrlOptions
39
     */
40
    abstract public function getUrlOptions(): UrlOptions;
41
42
    /**
43
     * Boot the trait.
44
     *
45
     * Check if the "getUrlOptions" method has been implemented on the underlying model class.
46
     * Eager load urls through anonymous global scope.
47
     * Trigger eloquent events to create, update, delete url.
48
     *
49
     * @return void
50
     */
51
    public static function bootHasUrl(): void
52
    {
53
        static::addGlobalScope('url', function (Builder $builder) {
54
            $builder->with('url');
55
        });
56
57
        static::created(function (Model $model) {
58
            if (self::$generateUrl === true) {
59
                $model->createUrl();
60
            }
61
        });
62
63
        static::updated(function (Model $model) {
64
            if (self::$generateUrl === true) {
65
                $model->updateUrl();
66
            }
67
        });
68
69
        static::saved(function (Model $model) {
0 ignored issues
show
Unused Code introduced by
The parameter $model is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
70
            if (self::$generateUrl === false) {
71
                self::$generateUrl = true;
72
            }
73
        });
74
75
        static::deleted(function (Model $model) {
76
            if ($model->forceDeleting !== false) {
77
                $model->deleteUrl();
78
            }
79
        });
80
    }
81
82
    /**
83
     * Get the model's url.
84
     *
85
     * @return MorphOne
86
     */
87
    public function url(): MorphOne
88
    {
89
        return $this->morphOne(Url::class, 'urlable');
0 ignored issues
show
Bug introduced by
It seems like morphOne() 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...
90
    }
91
92
    /**
93
     * Get the model's direct url string.
94
     *
95
     * @param bool|null $secure
96
     * @return \Illuminate\Contracts\Routing\UrlGenerator|string|null
97
     */
98
    public function getUrl(?bool $secure = null): ?string
99
    {
100
        if ($this->url && $this->url->exists) {
101
            return url($this->url->url, [], $secure);
0 ignored issues
show
Bug introduced by
The property url 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...
102
        }
103
104
        return null;
105
    }
106
107
    /**
108
     * Get the model's direct uri string.
109
     *
110
     * @return string|null
111
     */
112
    public function getUri(): ?string
113
    {
114
        return optional($this->url)->url ?: null;
115
    }
116
117
    /**
118
     * Disable the url generation manually only for the current request.
119
     *
120
     * @return static
121
     */
122
    public function doNotGenerateUrl(): self
123
    {
124
        self::$generateUrl = false;
125
126
        return $this;
127
    }
128
129
    /**
130
     * Get the options for the HasSlug trait.
131
     *
132
     * @return SlugOptions
133
     * @throws Exception
134
     */
135
    public function getSlugOptions(): SlugOptions
136
    {
137
        $this->initUrlOptions();
138
139
        return SlugOptions::instance()
140
            ->generateSlugFrom($this->urlOptions->fromField)
141
            ->saveSlugTo($this->urlOptions->toField);
142
    }
143
144
    /**
145
     * @return void
146
     * @throws Exception
147
     */
148
    public function saveUrl(): void
149
    {
150
        $this->initUrlOptions();
151
152
        if ($this->url && $this->url->exists) {
153
            $this->updateUrl();
154
        } else {
155
            $this->createUrl();
156
        }
157
    }
158
159
    /**
160
     * Create a new url for the model.
161
     *
162
     * @return void
163
     * @throws Exception
164
     */
165
    public function createUrl(): void
166
    {
167
        $this->initUrlOptions();
168
169
        if (! $this->getAttribute($this->urlOptions->toField)) {
0 ignored issues
show
Bug introduced by
It seems like getAttribute() 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...
170
            return;
171
        }
172
173
        try {
174
            $this->url()->create([
175
                'url' => $this->buildFullUrl(),
176
            ]);
177
        } catch (Exception $e) {
178
            throw UrlException::createFailed();
179
        }
180
    }
181
182
    /**
183
     * Update the existing url for the model.
184
     *
185
     * @return void
186
     * @throws Exception
187
     */
188
    public function updateUrl(): void
189
    {
190
        $this->initUrlOptions();
191
192
        if (! $this->getAttribute($this->urlOptions->toField)) {
0 ignored issues
show
Bug introduced by
It seems like getAttribute() 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...
193
            return;
194
        }
195
196
        try {
197
            DB::transaction(function () {
198
                if ($this->url()->count() == 0) {
199
                    $this->createUrl();
200
                }
201
202
                $this->url()->update([
0 ignored issues
show
Bug introduced by
The method update() does not exist on Illuminate\Database\Eloquent\Relations\MorphOne. Did you maybe mean rawUpdate()?

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...
203
                    'url' => $this->buildFullUrl(),
204
                ]);
205
206
                if ($this->urlOptions->cascadeUpdate === true) {
207
                    $this->updateUrlsInCascade();
208
                }
209
            });
210
        } catch (Exception $e) {
211
            throw UrlException::updateFailed();
212
        }
213
    }
214
215
    /**
216
     * Delete the url for the just deleted model.
217
     *
218
     * @return void
219
     * @throws UrlException
220
     */
221
    public function deleteUrl(): void
222
    {
223
        try {
224
            $this->url()->delete();
225
        } catch (Exception $e) {
226
            throw UrlException::deleteFailed();
227
        }
228
    }
229
230
    /**
231
     * Synchronize children urls for the actual model's url.
232
     * Saves all children urls of the model in use with the new parent model's slug.
233
     *
234
     * @return void
235
     */
236
    protected function updateUrlsInCascade(): void
237
    {
238
        $old = trim($this->getOriginal($this->urlOptions->toField), '/');
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...
239
        $new = trim($this->getAttribute($this->urlOptions->toField), '/');
0 ignored issues
show
Bug introduced by
It seems like getAttribute() 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...
240
241
        $children = URL::where('urlable_type', static::class)->where(function ($query) use ($old) {
242
            $query->where('url', 'like', "{$old}/%")->orWhere('url', 'like', "%/{$old}/%");
243
        })->get();
244
245
        foreach ($children as $child) {
246
            $child->update([
247
                'url' => str_replace($old.'/', $new.'/', $child->url),
248
            ]);
249
        }
250
    }
251
252
    /**
253
     * Get the full relative url.
254
     * The full url will also include the prefix and suffix if any was provided.
255
     *
256
     * @return string
257
     */
258
    protected function buildFullUrl(): string
259
    {
260
        $prefix = $this->buildUrlSegment('prefix');
261
        $suffix = $this->buildUrlSegment('suffix');
262
263
        return
264
            (Str::is('/', $prefix) ? '' : ($prefix ? $prefix.$this->urlOptions->urlGlue : '')).
265
            $this->getAttribute($this->urlOptions->toField).
0 ignored issues
show
Bug introduced by
It seems like getAttribute() 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...
266
            (Str::is('/', $suffix) ? '' : ($suffix ? $this->urlOptions->urlGlue.$suffix : ''));
267
    }
268
269
    /**
270
     * Build the url segment.
271
     * This can be either "prefix" or "suffix".
272
     * The accepted parameter $type accepts only "prefix" and "suffix" as it's value.
273
     * Otherwise, the method will return an empty string.
274
     *
275
     * @param string $type
276
     * @return string
277
     */
278
    protected function buildUrlSegment(string $type): string
279
    {
280
        if ($type != 'prefix' && $type != 'suffix') {
281
            return '';
282
        }
283
284
        $segment = $this->urlOptions->{'url'.ucwords($type)};
285
286
        if (is_callable($segment)) {
287
            return call_user_func_array($segment, [[], $this]);
288
        } elseif (is_array($segment)) {
289
            return implode($this->urlOptions->urlGlue, $segment);
290
        } elseif (is_string($segment)) {
291
            return $segment;
292
        } else {
293
            return '';
294
        }
295
    }
296
297
    /**
298
     * Both instantiate the url options as well as validate their contents.
299
     *
300
     * @return void
301
     * @throws Exception
302
     */
303
    protected function initUrlOptions(): void
304
    {
305
        if ($this->urlOptions === null) {
306
            $this->urlOptions = $this->getUrlOptions();
307
        }
308
309
        $this->validateUrlOptions();
310
    }
311
312
    /**
313
     * Check if mandatory slug options have been properly set from the model.
314
     * Check if $fromField and $toField have been set.
315
     *
316
     * @return void
317
     * @throws UrlException
318
     */
319
    protected function validateUrlOptions(): void
320
    {
321
        if (! $this->urlOptions->routeController || ! $this->urlOptions->routeAction) {
322
            throw UrlException::mandatoryRouting(static::class);
323
        }
324
325
        if (! $this->urlOptions->fromField) {
326
            throw UrlException::mandatoryFromField(static::class);
327
        }
328
329
        if (! $this->urlOptions->toField) {
330
            throw UrlException::mandatoryToField(static::class);
331
        }
332
    }
333
}
334