|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\Sluggable; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
|
6
|
|
|
use Illuminate\Support\Traits\Localizable; |
|
7
|
|
|
|
|
8
|
|
|
trait HasTranslatableSlug |
|
9
|
|
|
{ |
|
10
|
|
|
use HasSlug, Localizable; |
|
11
|
|
|
|
|
12
|
|
|
protected function getLocalesForSlug(): Collection |
|
13
|
|
|
{ |
|
14
|
|
|
$generateSlugFrom = $this->slugOptions->generateSlugFrom; |
|
15
|
|
|
|
|
16
|
|
|
if (is_callable($generateSlugFrom)) { |
|
17
|
|
|
// returns a collection of locales that were given to the SlugOptions object |
|
18
|
|
|
// when it was instantiated with the 'createWithLocales' method. |
|
19
|
|
|
return Collection::make($this->slugOptions->translatableLocales); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
// collects all locales for all translatable fields |
|
23
|
|
|
return Collection::wrap($generateSlugFrom) |
|
24
|
|
|
->filter(fn ($fieldName) => $this->isTranslatableAttribute($fieldName)) |
|
|
|
|
|
|
25
|
|
|
->flatMap(fn ($fieldName) => $this->getTranslatedLocales($fieldName)); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
protected function addSlug() |
|
29
|
|
|
{ |
|
30
|
|
|
$this->ensureValidSlugOptions(); |
|
31
|
|
|
|
|
32
|
|
|
$this->getLocalesForSlug()->unique()->each(function ($locale) { |
|
33
|
|
|
$this->withLocale($locale, function () use ($locale) { |
|
34
|
|
|
$slug = $this->generateNonUniqueSlug(); |
|
35
|
|
|
|
|
36
|
|
|
$slugField = $this->slugOptions->slugField; |
|
37
|
|
|
|
|
38
|
|
|
if ($this->slugOptions->generateUniqueSlugs) { |
|
39
|
|
|
// temporarly change the 'slugField' of the SlugOptions |
|
40
|
|
|
// so the 'otherRecordExistsWithSlug' method queries |
|
41
|
|
|
// the locale JSON column instead of the 'slugField'. |
|
42
|
|
|
$this->slugOptions->saveSlugsTo("{$slugField}->{$locale}"); |
|
43
|
|
|
|
|
44
|
|
|
$slug = $this->makeSlugUnique($slug); |
|
45
|
|
|
|
|
46
|
|
|
// revert the change for the next iteration |
|
47
|
|
|
$this->slugOptions->saveSlugsTo($slugField); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
$this->setTranslation($slugField, $locale, $slug); |
|
51
|
|
|
}); |
|
52
|
|
|
}); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
protected function getSlugSourceStringFromCallable(): string |
|
56
|
|
|
{ |
|
57
|
|
|
return call_user_func($this->slugOptions->generateSlugFrom, $this, $this->getLocale()); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
protected function hasCustomSlugBeenUsed(): bool |
|
61
|
|
|
{ |
|
62
|
|
|
return false; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|