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