|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace NovaListCard\Http\Controllers; |
|
4
|
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
|
6
|
|
|
use Illuminate\Routing\Controller; |
|
7
|
|
|
use Illuminate\Support\Facades\Cache; |
|
8
|
|
|
use Illuminate\Support\Facades\Response; |
|
9
|
|
|
use NovaListCard\Http\Requests\CardRequest; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @psalm-suppress UndefinedClass |
|
13
|
|
|
*/ |
|
14
|
|
|
class ResourceController extends Controller |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @param \NovaListCard\Http\Requests\CardRequest $cardRequest |
|
18
|
|
|
* @return mixed |
|
19
|
|
|
*/ |
|
20
|
4 |
|
public function __invoke(CardRequest $cardRequest) |
|
21
|
|
|
{ |
|
22
|
|
|
|
|
23
|
4 |
|
$callback = function () use ($cardRequest) { |
|
24
|
|
|
try { |
|
25
|
4 |
|
$resource = $cardRequest->cardResource(); |
|
|
|
|
|
|
26
|
1 |
|
} catch (\Exception $e) { |
|
27
|
1 |
|
return Response::json([ |
|
28
|
1 |
|
'message' => $e->getMessage(), |
|
29
|
1 |
|
], 404); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
3 |
|
return $cardRequest->cardResource()::indexQuery( |
|
33
|
3 |
|
$cardRequest, |
|
34
|
3 |
|
$cardRequest->prepareQuery() |
|
35
|
3 |
|
) |
|
36
|
3 |
|
->get() |
|
37
|
3 |
|
->mapInto($cardRequest->cardResource()) |
|
38
|
3 |
|
->filter(function ($resource) use ($cardRequest) { |
|
39
|
3 |
|
return $resource->authorizedToView($cardRequest); |
|
40
|
3 |
|
}) |
|
41
|
3 |
|
->map(callback: function ($resource) use ($cardRequest) { |
|
42
|
3 |
|
$data = [ |
|
43
|
3 |
|
'title' => $resource->title(), |
|
44
|
3 |
|
'url' => route('nova.pages.detail', [$resource::uriKey(), $resource->getKey()]), |
|
45
|
3 |
|
]; |
|
46
|
|
|
|
|
47
|
3 |
|
$card = $cardRequest->card(); |
|
48
|
|
|
|
|
49
|
3 |
|
if ($card->valueColumn) { |
|
50
|
3 |
|
$value = $resource->resource->{$card->valueColumn}; |
|
51
|
3 |
|
$data['value'] = match ($card->valueFormatter) { |
|
52
|
3 |
|
'datetime' => Carbon::parse($value)->format($card->valueFormat), |
|
53
|
3 |
|
'integer' => (int)$value, |
|
54
|
3 |
|
default => $value, |
|
55
|
3 |
|
}; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
3 |
|
if ($card->timestampColumn) { |
|
59
|
1 |
|
$data['timestamp'] = $resource->resource->{$card->timestampColumn}?->format($card->timestampFormat ?: 'Y-m-d'); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
3 |
|
return $data; |
|
63
|
3 |
|
}); |
|
64
|
4 |
|
}; |
|
65
|
|
|
|
|
66
|
4 |
|
if ($cacheFor = $cardRequest->card()?->cacheFor()) { |
|
67
|
1 |
|
return Cache::remember( |
|
68
|
1 |
|
$cardRequest->card()->getCacheKey($cardRequest), |
|
69
|
1 |
|
$cacheFor, |
|
70
|
1 |
|
$callback |
|
71
|
1 |
|
); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
3 |
|
return call_user_func($callback); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|