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