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