1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Imanghafoori\Widgets\Utils; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Debug\ExceptionHandler; |
6
|
|
|
|
7
|
|
|
class WidgetJsonifier |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @param $widget object|string |
11
|
|
|
* @param array $args |
12
|
|
|
* @return string |
13
|
|
|
*/ |
14
|
2 |
|
public function jsonResponse($widget, ...$args) |
15
|
|
|
{ |
16
|
2 |
|
if (is_string($widget)) { |
17
|
1 |
|
$widget = $this->makeWidgetObj($widget); |
18
|
|
|
} |
19
|
|
|
|
20
|
2 |
|
app(Normalizer::class)->normalizeWidgetConfig($widget); |
21
|
|
|
|
22
|
|
|
try { |
23
|
2 |
|
$json = $this->generateJson($widget, ...$args); |
24
|
|
|
} catch (\Exception $e) { |
25
|
|
|
return app()->make(ExceptionHandler::class)->render(app('request'), $e)->send(); |
26
|
|
|
} |
27
|
|
|
|
28
|
2 |
|
return $json; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param $widget string |
33
|
|
|
* @return object |
34
|
|
|
*/ |
35
|
1 |
|
private function makeWidgetObj(string $widget) |
36
|
|
|
{ |
37
|
1 |
|
$widget = app()->getNamespace().'Widgets\\'.$widget; |
|
|
|
|
38
|
|
|
|
39
|
1 |
|
return app($widget); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* It tries to get the html from cache if possible, otherwise generates it. |
44
|
|
|
* |
45
|
|
|
* @param $widget object |
46
|
|
|
* @param array ...$args |
47
|
|
|
* @return string |
48
|
|
|
*/ |
49
|
|
|
private function generateJson($widget, ...$args) |
50
|
|
|
{ |
51
|
|
|
// Everything inside this function is executed only when the cache is not available. |
52
|
2 |
|
$expensivePhpCode = function () use ($widget, $args) { |
53
|
2 |
|
$data = \App::call($widget->controller, ...$args); |
|
|
|
|
54
|
|
|
|
55
|
|
|
// render the template with the resulting data. |
56
|
2 |
|
return response()->json($data, 200); |
57
|
2 |
|
}; |
58
|
|
|
|
59
|
|
|
// We first try to get the output from the cache before trying to run the expensive $expensivePhpCode... |
60
|
|
|
if (app(Policies::class)->widgetShouldUseCache()) { |
61
|
|
|
return app(Cache::class)->cacheResult($args, $expensivePhpCode, $widget, 'json'); |
|
|
|
|
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $expensivePhpCode(); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|