|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Urls; |
|
4
|
|
|
|
|
5
|
|
|
use Thinktomorrow\Chief\Fields\Fields; |
|
6
|
|
|
use Thinktomorrow\Chief\Urls\ProvidesUrl\ProvidesUrl; |
|
7
|
|
|
|
|
8
|
|
|
class UrlSlugFields extends Fields |
|
9
|
|
|
{ |
|
10
|
66 |
|
public static function fromModel(ProvidesUrl $model) |
|
11
|
|
|
{ |
|
12
|
66 |
|
$fields = self::initEmptyFields($model->availableLocales(), $model); |
|
|
|
|
|
|
13
|
|
|
|
|
14
|
66 |
|
self::fillWithExistingValues($model, $fields); |
|
15
|
|
|
|
|
16
|
66 |
|
return $fields; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function toJson(): string |
|
20
|
|
|
{ |
|
21
|
|
|
return json_encode($this->toArray()); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
1 |
|
public function toArray(): array |
|
25
|
|
|
{ |
|
26
|
1 |
|
$array = []; |
|
27
|
|
|
|
|
28
|
1 |
|
foreach ($this->all() as $field) { |
|
29
|
1 |
|
$array[] = $field->toArray(); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
1 |
|
return $array; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param array $locales |
|
37
|
|
|
* @param ProvidesUrl $model |
|
38
|
|
|
* @return UrlSlugFields |
|
39
|
|
|
*/ |
|
40
|
66 |
|
private static function initEmptyFields(array $locales, ProvidesUrl $model): self |
|
41
|
|
|
{ |
|
42
|
66 |
|
$fields = new static([]); |
|
43
|
|
|
|
|
44
|
66 |
|
foreach ($locales as $locale) { |
|
45
|
66 |
|
$fields['url-slugs.' . $locale] = UrlSlugField::make('url-slugs.' . $locale) |
|
46
|
66 |
|
->setBaseUrlSegment($model->baseUrlSegment($locale)) |
|
47
|
66 |
|
->prepend($model->resolveUrl($locale, $model->baseUrlSegment($locale)) .'/') |
|
|
|
|
|
|
48
|
66 |
|
->name('url-slugs[' . $locale . ']') |
|
|
|
|
|
|
49
|
66 |
|
->label($locale); |
|
|
|
|
|
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
66 |
|
return $fields; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @param ProvidesUrl $model |
|
57
|
|
|
* @param $fields |
|
58
|
|
|
*/ |
|
59
|
66 |
|
private static function fillWithExistingValues(ProvidesUrl $model, self $fields): void |
|
60
|
|
|
{ |
|
61
|
|
|
$records = MemoizedUrlRecord::getByModel($model)->reject(function ($record) { |
|
62
|
21 |
|
return $record->isRedirect(); |
|
63
|
66 |
|
})->sortBy('locale'); |
|
64
|
|
|
|
|
65
|
66 |
|
foreach ($records as $record) { |
|
66
|
21 |
|
if (!isset($fields['url-slugs.'.$record->locale])) { |
|
67
|
|
|
continue; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
21 |
|
$fields['url-slugs.'.$record->locale] |
|
71
|
21 |
|
->setUrlRecord($record) |
|
|
|
|
|
|
72
|
21 |
|
->setBaseUrlSegment($model->baseUrlSegment($record->locale)) |
|
73
|
21 |
|
->prepend($model->resolveUrl($record->locale, $model->baseUrlSegment($record->locale)) .'/'); |
|
74
|
|
|
} |
|
75
|
66 |
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|