-
Notifications
You must be signed in to change notification settings - Fork 554
/
TwillUtil.php
106 lines (82 loc) · 2.73 KB
/
TwillUtil.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace A17\Twill;
use A17\Twill\Models\Contracts\TwillLinkableModel;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Session;
/**
* @todo: This could "pile up" over time. Maybe we can clear it when a new form is being built.
*/
class TwillUtil
{
/**
* @var string
*/
private const SESSION_FIELD = 'twill_util';
/**
* @var string
*/
private const REPEATER_ID_INDEX = 'repeater_ids';
/**
* @var string
*/
private const BLOCK_ID_INDEX = 'block_ids';
public function hasRepeaterIdFor(int $frontEndId): ?int
{
return $this->getFromTempStore(self::REPEATER_ID_INDEX, $frontEndId);
}
public function registerRepeaterId(int $frontEndId, int $dbId): self
{
$this->pushToTempStore(self::REPEATER_ID_INDEX, $frontEndId, $dbId);
return $this;
}
public function hasBlockIdFor(int $frontEndId): ?int
{
return $this->getFromTempStore(self::BLOCK_ID_INDEX, $frontEndId);
}
public function registerBlockId(int $frontEndId, int $dbId): self
{
$this->pushToTempStore(self::BLOCK_ID_INDEX, $frontEndId, $dbId);
return $this;
}
public function clearTempStore(): void
{
Session::remove(self::SESSION_FIELD);
}
public function parseInternalLinks(string $content): string
{
return preg_replace_callback(
'/(#twillInternalLink::(.*?)#(\d+))/',
function (array $data) {
if (isset($data[2], $data[3])) {
$modelClass = $data[2];
$id = $data[3];
if (array_key_exists($modelClass, Relation::morphMap())) {
$modelClass = Relation::morphMap()[$modelClass];
}
$model = $modelClass::published()->where('id', $id)->first();
if (!$model) {
return url('404');
}
if ($model instanceof TwillLinkableModel) {
return $model->getFullUrl();
}
return url($model->slug);
}
},
$content
);
}
private function getFromTempStore(string $key, int $frontendId): ?int
{
$data = Session::get(self::SESSION_FIELD, []);
return $data[$key][$frontendId] ?? null;
}
private function pushToTempStore(string $key, int $frontendId, int $dbId): void
{
$sessionData = Session::get(self::SESSION_FIELD, []);
$keyData = $sessionData[$key] ?? [];
$keyData[$frontendId] = $dbId;
$sessionData[$key] = $keyData;
Session::put(self::SESSION_FIELD, $sessionData);
}
}