1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Thinktomorrow\Chief\Urls; |
4
|
|
|
|
5
|
|
|
use Thinktomorrow\Chief\Fields\Types\InputField; |
6
|
|
|
|
7
|
|
|
class UrlSlugField extends InputField |
8
|
|
|
{ |
9
|
|
|
private $urlRecord; |
10
|
|
|
|
11
|
|
|
private $baseUrlSegment; |
12
|
|
|
|
13
|
|
|
private $fullUrl; |
14
|
|
|
|
15
|
|
|
public function setUrlRecord(UrlRecord $urlRecord) |
16
|
|
|
{ |
17
|
|
|
$this->urlRecord = $urlRecord; |
18
|
|
|
|
19
|
|
|
return $this; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function getUrlRecordId(): int |
23
|
|
|
{ |
24
|
|
|
return $this->urlRecord->id; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function setBaseUrlSegment($baseUrlSegment = null) |
28
|
|
|
{ |
29
|
|
|
$this->baseUrlSegment = $baseUrlSegment; |
30
|
|
|
|
31
|
|
|
return $this; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function value() |
35
|
|
|
{ |
36
|
|
|
return old($this->key, $this->rawSlugValue()); |
|
|
|
|
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function fullUrl(): string |
40
|
|
|
{ |
41
|
|
|
return $this->fullUrl |
42
|
|
|
? $this->fullUrl |
43
|
|
|
: $this->prepend.$this->value(); |
|
|
|
|
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function setFullUrl(string $fullUrl) |
47
|
|
|
{ |
48
|
|
|
$this->fullUrl = $fullUrl; |
49
|
|
|
|
50
|
|
|
return $this; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function rawSlugValue(): string |
54
|
|
|
{ |
55
|
|
|
if (!$this->urlRecord) { |
56
|
|
|
return ''; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$slug = $this->urlRecord->slug; |
60
|
|
|
|
61
|
|
|
// If this is a '/' slug, it indicates the homepage for this locale. In this case, |
62
|
|
|
// we wont be trimming the slash |
63
|
|
|
if ($slug === '/') { |
64
|
|
|
return $slug; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if ($this->startsWithBaseUrlSegment($slug)) { |
68
|
|
|
$slug = trim(substr($slug, strlen($this->baseUrlSegment)), '/'); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return $slug; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @param $value |
76
|
|
|
* @return bool |
77
|
|
|
*/ |
78
|
|
|
private function startsWithBaseUrlSegment($value): bool |
79
|
|
|
{ |
80
|
|
|
return ($this->baseUrlSegment && 0 === strpos($value, $this->baseUrlSegment)); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function toArray(): array |
84
|
|
|
{ |
85
|
|
|
return array_merge($this->values, [ |
86
|
|
|
'key' => $this->key, |
|
|
|
|
87
|
|
|
'prepend' => $this->prepend, |
|
|
|
|
88
|
|
|
'label' => $this->label, |
|
|
|
|
89
|
|
|
'placeholder' => $this->placeholder, |
|
|
|
|
90
|
|
|
'description' => $this->description, |
|
|
|
|
91
|
|
|
'value' => $this->value(), |
92
|
|
|
'baseUrlSegment' => $this->baseUrlSegment, |
93
|
|
|
'hint' => null, // Hint placeholder to show url hint when it already exists |
94
|
|
|
'is_homepage' => ($this->value() === '/'), |
95
|
|
|
'show' => !!$this->value(),// show input field or not |
96
|
|
|
]); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|