Passed
Push — master ( b7736e...36606a )
by Iman
02:00
created

WidgetJsonifier::jsonResponse()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.1406

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 16
ccs 6
cts 8
cp 0.75
crap 3.1406
rs 9.4285
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)->normalizeJsonWidget($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 object
33
     * @return \Illuminate\Foundation\Application|mixed
34
     */
35 1
    private function makeWidgetObj($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
     *
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 2
        $expensivePhpCode = function () use ($widget, $args) {
54 2
            $data = \App::call($widget->controller, ...$args);
55
56
            // render the template with the resulting data.
57 2
            return response()->json($data, 200);
58 2
        };
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