-
-
Notifications
You must be signed in to change notification settings - Fork 641
Expand file tree
/
Copy pathSharedPreview.php
More file actions
91 lines (71 loc) · 2.51 KB
/
Copy pathSharedPreview.php
File metadata and controls
91 lines (71 loc) · 2.51 KB
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
<?php
namespace Statamic\CP;
use Statamic\Contracts\Tokens\Token as TokenContract;
use Statamic\Facades\Data;
use Statamic\Facades\Token;
use Statamic\Facades\URL;
use Statamic\Tokens\Handlers\SharedPreview as Handler;
class SharedPreview
{
public function tokenize($item, ?int $revision = null): TokenContract
{
if ($existing = $this->existing($item, $revision)) {
return $existing;
}
$minutes = (int) config('statamic.live_preview.shared_link_expiry', 1440);
$data = ['reference' => $item->reference()];
if ($revision) {
$data['revision'] = $revision;
}
return tap(
Token::make(null, Handler::class, $data)->expireAt(now()->addMinutes($minutes))
)->save();
}
public function existing($item, ?int $revision = null): ?TokenContract
{
return Token::all()->first(function ($token) use ($item, $revision) {
return $token->handler() === Handler::class
&& ! $token->hasExpired()
&& $token->get('reference') === $item->reference()
&& $token->get('revision') == $revision;
});
}
public function item(TokenContract $token)
{
$item = Data::find($token->get('reference'));
if (! $item) {
return null;
}
if ($timestamp = $token->get('revision')) {
$revision = $this->findRevision($item, $timestamp);
return $revision ? $item->makeFromRevision($revision) : false;
}
if (
method_exists($item, 'hasWorkingCopy')
&& $item->revisionsEnabled()
&& $item->hasWorkingCopy()
) {
return $item->fromWorkingCopy();
}
return $item;
}
public function url($item, TokenContract $token, int $target = 0): string
{
$preview = $this->item($token);
if (! $preview) {
$preview = $item;
}
$targets = method_exists($preview, 'previewTargets') ? $preview->previewTargets() : collect();
$url = URL::makeAbsolute($targets[$target]['url'] ?? $preview->absoluteUrl());
return $url.(str_contains((string) $url, '?') ? '&' : '?').'token='.$token->token();
}
public function findRevision($item, $timestamp)
{
if (! method_exists($item, 'revisions')) {
return null;
}
return $item->revisions()->first(
fn ($revision) => (int) $revision->date()->timestamp === (int) $timestamp
);
}
}