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
|
|
View Code Duplication |
public function jsonResponse($widget, ...$args) |
|
|
|
|
15
|
|
|
{ |
16
|
|
|
if (is_string($widget)) { |
17
|
|
|
$widget = $this->makeWidgetObj($widget); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
app(Normalizer::class)->normalizeJsonWidget($widget); |
21
|
|
|
|
22
|
|
|
try { |
23
|
|
|
$json = $this->generateJson($widget, ...$args); |
24
|
|
|
} catch (\Exception $e) { |
25
|
|
|
return app()->make(ExceptionHandler::class)->render(app('request'), $e)->send(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
return $json; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param $widget object |
33
|
|
|
* @return \Illuminate\Foundation\Application|mixed |
34
|
|
|
*/ |
35
|
|
|
private function makeWidgetObj($widget) |
36
|
|
|
{ |
37
|
|
|
$widget = app()->getNamespace().'Widgets\\'.$widget; |
38
|
|
|
|
39
|
|
|
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
|
|
|
* |
48
|
|
|
* @return string |
49
|
|
|
*/ |
50
|
|
|
private function generateJson($widget, ...$args) |
51
|
|
|
{ |
52
|
|
|
// Everything inside this function is executed only when the cache is not available. |
53
|
|
|
$expensivePhpCode = function () use ($widget, $args) { |
54
|
|
|
$data = \App::call($widget->controller, ...$args); |
55
|
|
|
|
56
|
|
|
// render the template with the resulting data. |
57
|
|
|
return response()->json($data, 200); |
58
|
|
|
}; |
59
|
|
|
|
60
|
|
|
// We first try to get the output from the cache before trying to run the expensive $expensivePhpCode... |
61
|
|
|
if (app(Policies::class)->widgetShouldUseCache()) { |
62
|
|
|
return app(Cache::class)->cacheResult($args, $expensivePhpCode, $widget, 'json'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $expensivePhpCode(); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.