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