Passed
Pull Request — 2.x (#586)
by Bekzat
04:25
created

HasSlug::bootHasSlug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.125

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 0
dl 0
loc 12
ccs 3
cts 6
cp 0.5
crap 1.125
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace A17\Twill\Models\Behaviors;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Support\Facades\DB;
7
8
9
trait HasSlug
10
{
11
    private $nb_variation_slug = 3;
12
13 1
    protected static function bootHasSlug()
14
    {
15
        static::created(function ($model) {
16
            $model->setSlugs();
17 1
        });
18
19
        static::updated(function ($model) {
20
            $model->setSlugs();
21 1
        });
22
23
        static::restored(function ($model) {
24
            $model->setSlugs($restoring = true);
25 1
        });
26 1
    }
27
28
    public function slugs()
29
    {
30
        return $this->hasMany(
0 ignored issues
show
Bug introduced by
It seems like hasMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

30
        return $this->/** @scrutinizer ignore-call */ hasMany(
Loading history...
31
            config('twill.namespace') . "\Models\Slugs\\" . $this->getSlugClassName()
32
        );
33
    }
34
35
    public function getSlugClass()
36
    {
37
        $slugClassName = config('twill.namespace') . "\Models\Slugs\\" . $this->getSlugClassName();
38
        return new $slugClassName;
39
    }
40
41
    protected function getSlugClassName()
42
    {
43
        return class_basename($this) . "Slug";
44
    }
45
46
    public function scopeForSlug($query, $slug)
47
    {
48
        return $query->whereHas('slugs', function ($query) use ($slug) {
49
            $query->whereSlug($slug);
50
            $query->whereActive(true);
51
            $query->whereLocale(app()->getLocale());
0 ignored issues
show
introduced by
The method getLocale() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
            $query->whereLocale(app()->/** @scrutinizer ignore-call */ getLocale());
Loading history...
52
        })->with(['slugs']);
53
    }
54
55
    public function scopeForInactiveSlug($query, $slug)
56
    {
57
        return $query->whereHas('slugs', function ($query) use ($slug) {
58
            $query->whereSlug($slug);
59
            $query->whereLocale(app()->getLocale());
60
        })->with(['slugs']);
61
    }
62
63
    public function scopeForFallbackLocaleSlug($query, $slug)
64
    {
65
        return $query->whereHas('slugs', function ($query) use ($slug) {
66
            $query->whereSlug($slug);
67
            $query->whereActive(true);
68
            $query->whereLocale(config('translatable.fallback_locale'));
69
        })->with(['slugs']);
70
    }
71
72
    public function setSlugs($restoring = false)
73
    {
74
        foreach ($this->getSlugParams() as $slugParams) {
75
            $this->updateOrNewSlug($slugParams, $restoring);
76
        }
77
    }
78
79
    public function updateOrNewSlug($slugParams, $restoring = false)
80
    {
81
        if (in_array($slugParams['locale'], config('twill.slug_utf8_languages', []))) {
82
            $slugParams['slug'] = $this->getUtf8Slug($slugParams['slug']);
83
        } else {
84
            $slugParams['slug'] = Str::slug($slugParams['slug']);
85
        }
86
87
        //active old slug if already existing or create a new one
88
        if ((($oldSlug = $this->getExistingSlug($slugParams)) != null)
89
            && ($restoring ? $slugParams['slug'] === $this->suffixSlugIfExisting($slugParams) : true)) {
90
            if (!$oldSlug->active && ($slugParams['active'] ?? false)) {
91
                DB::table($this->getSlugsTable())->where('id', $oldSlug->id)->update(['active' => 1]);
92
                $this->disableLocaleSlugs($oldSlug->locale, $oldSlug->id);
93
            }
94
        } else {
95
96
            $this->addOneSlug($slugParams);
97
        }
98
    }
99
100
    public function getExistingSlug($slugParams)
101
    {
102
        $query = DB::table($this->getSlugsTable())->where($this->getForeignKey(), $this->id);
103
        unset($slugParams['active']);
104
105
        foreach ($slugParams as $key => $value) {
106
            //check variations of the slug
107
            if ($key == 'slug') {
108
                $query->where(function ($query) use ($value) {
109
                    $query->orWhere('slug', $value);
110
                    $query->orWhere('slug', $value . '-' . $this->getSuffixSlug());
111
                    for ($i = 2; $i <= $this->nb_variation_slug; $i++) {
112
                        $query->orWhere('slug', $value . '-' . $i);
113
                    }
114
                });
115
            } else {
116
                $query->where($key, $value);
117
            }
118
        }
119
120
        return $query->first();
121
    }
122
123
    protected function addOneSlug($slugParams)
124
    {
125
        $datas = [];
126
        foreach ($slugParams as $key => $value) {
127
            $datas[$key] = $value;
128
        }
129
130
        $datas['slug'] = $this->suffixSlugIfExisting($slugParams);
131
132
        $datas[$this->getForeignKey()] = $this->id;
133
134
        $id = DB::table($this->getSlugsTable())->insertGetId($datas);
135
136
        $this->disableLocaleSlugs($slugParams['locale'], $id);
137
    }
138
139
    public function disableLocaleSlugs($locale, $except_slug_id = 0)
140
    {
141
        DB::table($this->getSlugsTable())
142
            ->where($this->getForeignKey(), $this->id)
143
            ->where('id', '<>', $except_slug_id)
144
            ->where('locale', $locale)
145
            ->update(['active' => 0])
146
        ;
147
    }
148
149
    private function suffixSlugIfExisting($slugParams)
150
    {
151
        $slugBackup = $slugParams['slug'];
152
        $table = $this->getSlugsTable();
153
154
        unset($slugParams['active']);
155
156
        for ($i = 2; $i <= $this->nb_variation_slug + 1; $i++) {
157
            $qCheck = DB::table($table);
158
            $qCheck->whereNull($this->getDeletedAtColumn());
0 ignored issues
show
Bug introduced by
It seems like getDeletedAtColumn() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

158
            $qCheck->whereNull($this->/** @scrutinizer ignore-call */ getDeletedAtColumn());
Loading history...
159
            foreach ($slugParams as $key => $value) {
160
                $qCheck->where($key, '=', $value);
161
            }
162
163
            if ($qCheck->first() == null) {
164
                break;
165
            }
166
167
            if (!empty($slugParams['slug'])) {
168
                $slugParams['slug'] = $slugBackup . (($i > $this->nb_variation_slug) ? "-" . $this->getSuffixSlug() : "-{$i}");
169
            }
170
        }
171
172
        return $slugParams['slug'];
173
    }
174
175
    public function getActiveSlug($locale = null)
176
    {
177
        return $this->slugs->first(function ($slug) use ($locale) {
178
            return ($slug->locale === ($locale ?? app()->getLocale())) && $slug->active;
179
        }) ?? null;
180
    }
181
182
    public function getFallbackActiveSlug()
183
    {
184
        return $this->slugs->first(function ($slug) {
185
            return $slug->locale === config('translatable.fallback_locale') && $slug->active;
186
        }) ?? null;
187
    }
188
189
    public function getSlug($locale = null)
190
    {
191
        if (($slug = $this->getActiveSlug($locale)) != null) {
192
            return $slug->slug;
193
        }
194
195
        if (config('translatable.use_property_fallback', false) && (($slug = $this->getFallbackActiveSlug()) != null)) {
196
            return $slug->slug;
197
        }
198
199
        return "";
200
    }
201
202
    public function getSlugAttribute()
203
    {
204
        return $this->getSlug();
205
    }
206
207
    public function getSlugParams($locale = null)
208
    {
209
        if (count(getLocales()) === 1 || !isset($this->translations)) {
210
            $slugParams = $this->getSingleSlugParams($locale);
211
            if ($slugParams != null && !empty($slugParams)) {
212
                return $slugParams;
213
            }
214
        }
215
216
        $slugParams = [];
217
        foreach ($this->translations as $translation) {
218
            if ($translation->locale == $locale || $locale == null) {
219
                $attributes = $this->slugAttributes;
220
221
                $slugAttribute = array_shift($attributes);
222
223
                $slugDependenciesAttributes = [];
224
                foreach ($attributes as $attribute) {
225
                    if (!isset($this->$attribute)) {
226
                        throw new \Exception("You must define the field {$attribute} in your model");
227
                    }
228
229
                    $slugDependenciesAttributes[$attribute] = $this->$attribute;
230
                }
231
232
                if (!isset($translation->$slugAttribute) && !isset($this->$slugAttribute)) {
233
                    throw new \Exception("You must define the field {$slugAttribute} in your model");
234
                }
235
236
                $slugParam = [
237
                    'active' => $translation->active,
238
                    'slug' => $translation->$slugAttribute ?? $this->$slugAttribute,
239
                    'locale' => $translation->locale,
240
                ] + $slugDependenciesAttributes;
241
242
                if ($locale != null) {
243
                    return $slugParam;
244
                }
245
246
                $slugParams[] = $slugParam;
247
            }
248
        }
249
250
        return $locale == null ? $slugParams : null;
251
    }
252
253
    public function getSingleSlugParams($locale = null)
254
    {
255
        $slugParams = [];
256
        foreach (getLocales() as $appLocale) {
257
            if ($appLocale == $locale || $locale == null) {
258
                $attributes = $this->slugAttributes;
259
                $slugAttribute = array_shift($attributes);
260
                $slugDependenciesAttributes = [];
261
                foreach ($attributes as $attribute) {
262
                    if (!isset($this->$attribute)) {
263
                        throw new \Exception("You must define the field {$attribute} in your model");
264
                    }
265
266
                    $slugDependenciesAttributes[$attribute] = $this->$attribute;
267
                }
268
269
                if (!isset($this->$slugAttribute)) {
270
                    throw new \Exception("You must define the field {$slugAttribute} in your model");
271
                }
272
273
                $slugParam = [
274
                    'active' => 1,
275
                    'slug' => $this->$slugAttribute,
276
                    'locale' => $appLocale,
277
                ] + $slugDependenciesAttributes;
278
279
                if ($locale != null) {
280
                    return $slugParam;
281
                }
282
283
                $slugParams[] = $slugParam;
284
            }
285
        }
286
287
        return $locale == null ? $slugParams : null;
288
    }
289
290
    public function getSlugsTable()
291
    {
292
        return $this->slugs()->getRelated()->getTable();
293
    }
294
295
    public function getForeignKey()
296
    {
297
        return Str::snake(class_basename(get_class($this))) . "_id";
298
    }
299
300
    protected function getSuffixSlug()
301
    {
302
        return $this->id;
303
    }
304
305
    public function getUtf8Slug($str, $options = [])
306
    {
307
        // Make sure string is in UTF-8 and strip invalid UTF-8 characters
308
        $str = mb_convert_encoding((string) $str, 'UTF-8', mb_list_encodings());
309
310
        $defaults = array(
311
            'delimiter' => '-',
312
            'limit' => null,
313
            'lowercase' => true,
314
            'replacements' => array(),
315
            'transliterate' => true,
316
        );
317
318
        // Merge options
319
        $options = array_merge($defaults, $options);
320
321
        $char_map = array(
322
            // Latin
323
            'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
324
            'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
325
            'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
326
            'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
327
            'ß' => 'ss',
328
            'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
329
            'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
330
            'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
331
            'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
332
            'ÿ' => 'y',
333
334
            // Latin symbols
335
            '©' => '(c)',
336
337
            // Greek
338
            'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8',
339
            'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',
340
            'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W',
341
            'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I',
342
            'Ϋ' => 'Y',
343
            'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8',
344
            'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p',
345
            'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w',
346
            'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's',
347
            'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',
348
349
            // Turkish
350
            'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
351
            'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g',
352
353
            // Russian
354
            'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
355
            'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
356
            'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
357
            'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
358
            'Я' => 'Ya',
359
            'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
360
            'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
361
            'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
362
            'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
363
            'я' => 'ya',
364
365
            // Ukrainian
366
            'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
367
            'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',
368
369
            // Kazakh
370
            'Ә' => 'A', 'Ғ' => 'G', 'Қ' => 'Q', 'Ң' => 'N', 'Ө' => 'O', 'Ұ' => 'U',
371
            'ә' => 'a', 'ғ' => 'g', 'қ' => 'q', 'ң' => 'n', 'ө' => 'o', 'ұ' => 'u',
372
373
            // Czech
374
            'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U',
375
            'Ž' => 'Z',
376
            'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
377
            'ž' => 'z',
378
379
            // Polish
380
            'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z',
381
            'Ż' => 'Z',
382
            'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
383
            'ż' => 'z',
384
385
            // Latvian
386
            'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N',
387
            'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
388
            'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
389
            'š' => 's', 'ū' => 'u', 'ž' => 'z',
390
391
            // Romanian
392
            'Ă' => 'A', 'Â' => 'A', 'Î' => 'I', 'Ș' => 'S', 'Ț' => 'T',
393
            'ă' => 'a', 'â' => 'a', 'î' => 'i', 'ș' => 's', 'ț' => 't',
394
        );
395
396
        // Make custom replacements
397
        $str = preg_replace(array_keys($options['replacements']), $options['replacements'], $str);
398
399
        // Transliterate characters to ASCII
400
        if ($options['transliterate']) {
401
            $str = str_replace(array_keys($char_map), $char_map, $str);
402
        }
403
404
        // Replace non-alphanumeric characters with our delimiter
405
        $str = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $str);
406
407
        // Remove duplicate delimiters
408
        $str = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $str);
409
410
        // Truncate slug to max. characters
411
        $str = mb_substr($str, 0, ($options['limit'] ? $options['limit'] : mb_strlen($str, 'UTF-8')), 'UTF-8');
412
413
        // Remove delimiter from ends
414
        $str = trim($str, $options['delimiter']);
415
416
        return $options['lowercase'] ? mb_strtolower($str, 'UTF-8') : $str;
417
    }
418
419
    public function urlSlugShorter($string)
420
    {
421
        return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
422
    }
423
}
424