Completed
Push — master ( 1c625d...234c6d )
by Iman
01:39
created

WidgetJsonifier::_generateJson()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
nc 2
nop 2
dl 0
loc 16
rs 9.4285
c 1
b 0
f 0
1
<?php
2
3
namespace Imanghafoori\Widgets\Utils;
4
5
use Illuminate\Contracts\Debug\ExceptionHandler;
6
7
class WidgetJsonifier
8
{
9
10
    /**
11
     * @param $widget object|string
12
     * @param array $args
13
     * @return string
14
     */
15 View Code Duplication
    public function jsonResponse($widget, ...$args)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
16
    {
17
        if (is_string($widget)) {
18
            $widget = $this->_makeWidgetObj($widget);
19
        }
20
21
        app(Normalizer::class)->normalizeJsonWidget($widget);
22
23
        try {
24
            $json = $this->_generateJson($widget, ...$args);
25
        } catch (\Exception $e) {
26
            return app()->make(ExceptionHandler::class)->render(app('request'), $e)->send();
27
        }
28
29
        return $json;
30
    }
31
32
    /**
33
     * It tries to get the html from cache if possible, otherwise generates it.
34
     *
35
     * @param $widget object
36
     * @param array ...$args
37
     *
38
     * @return string
39
     */
40
    private function _generateJson($widget, ...$args)
41
    {
42
        // Everything inside this function is executed only when the cache is not available.
43
        $expensivePhpCode = function () use ($widget, $args) {
44
            $data = \App::call($widget->controller, ...$args);
45
            // render the template with the resulting data.
46
            return response()->json($data, 200);
47
        };
48
49
        // We first try to get the output from the cache before trying to run the expensive $expensivePhpCode...
50
        if (app(Policies::class)->widgetShouldUseCache()) {
51
            return app(Cache::class)->cacheResult($args, $expensivePhpCode, $widget, 'json');
52
        }
53
54
        return $expensivePhpCode();
55
    }
56
57
58
    /**
59
     * @param $widget object
60
     * @return \Illuminate\Foundation\Application|mixed
61
     */
62
    private function _makeWidgetObj($widget)
63
    {
64
        $widget = app()->getNamespace().'Widgets\\'.$widget;
65
        return app($widget);
66
    }
67
}
68