Passed
Push — master ( e2c3a7...b7736e )
by Iman
01:52
created

WidgetJsonifier   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 60%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 61
ccs 9
cts 15
cp 0.6
rs 10
c 2
b 0
f 0
wmc 6
lcom 0
cbo 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A jsonResponse() 0 16 3
A makeWidgetObj() 0 6 1
A generateJson() 0 17 2
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 1
    public function jsonResponse($widget, ...$args)
15
    {
16 1
        if (is_string($widget)) {
17
            $widget = $this->makeWidgetObj($widget);
18
        }
19
20 1
        app(Normalizer::class)->normalizeJsonWidget($widget);
21
22
        try {
23 1
            $json = $this->generateJson($widget, ...$args);
24
        } catch (\Exception $e) {
25
            return app()->make(ExceptionHandler::class)->render(app('request'), $e)->send();
26
        }
27
28 1
        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 1
        $expensivePhpCode = function () use ($widget, $args) {
54 1
            $data = \App::call($widget->controller, ...$args);
55
56
            // render the template with the resulting data.
57 1
            return response()->json($data, 200);
58 1
        };
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