Passed
Push — master ( a2bfb8...a4c3d2 )
by Iman
05:03
created

WidgetRenderer   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 148
Duplicated Lines 0 %

Test Coverage

Coverage 86%

Importance

Changes 16
Bugs 5 Features 0
Metric Value
eloc 47
c 16
b 5
f 0
dl 0
loc 148
ccs 43
cts 50
cp 0.86
rs 10
wmc 19

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A generateHtml() 0 15 2
A makeWidgetObj() 0 9 2
A renderWidget() 0 19 4
A renderTemplate() 0 23 4
A callController() 0 12 4
A makeDataForView() 0 14 2
1
<?php
2
3
namespace Imanghafoori\Widgets\Utils;
4
5
use Illuminate\Support\Str;
6
7
class WidgetRenderer
8
{
9
    public $html;
10
11
    private $_viewData;
12
13
    private $_policies;
14
15
    /**
16
     * BaseWidget constructor.
17
     */
18 20
    public function __construct()
19
    {
20 20
        $this->_policies = resolve(Policies::class);
21 20
    }
22
23
    /**
24
     * @param $widget object|string
25
     * @param array $args
26
     * @return string
27
     */
28 20
    public function renderWidget($widget, ...$args)
29
    {
30 20
        if (is_string($widget)) {
31 1
            $widget = $this->makeWidgetObj($widget);
32
        }
33
34 20
        if (is_array($widget)) {
35
            $widget = (object) $widget;
36
        }
37
38 20
        event('widgetize.rendering_widget', [$widget]);
39
40 20
        resolve(Normalizer::class)->normalizeWidgetConfig($widget);
41
42 20
        if (app()->offsetExists('debugbar')) {
43
            app('widgetize.debugger')->addMessage(['widget class:' => $widget, 'args:' => $args]);
44
        }
45
46 20
        return $this->generateHtml($widget, ...$args);
47
    }
48
49
    /**
50
     * @param $widget object
51
     * @return \Illuminate\Foundation\Application|mixed
52
     */
53 1
    private function makeWidgetObj($widget)
54
    {
55 1
        if (Str::startsWith($widget, ['\\'])) {
56
            return resolve($widget);
57
        }
58
59 1
        $widget = app()->getNamespace().'Widgets\\'.$widget;
0 ignored issues
show
introduced by
The method getNamespace() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

59
        $widget = app()->/** @scrutinizer ignore-call */ getNamespace().'Widgets\\'.$widget;
Loading history...
60
61 1
        return resolve($widget);
62
    }
63
64
    /**
65
     * It tries to get the html from cache if possible, otherwise generates it.
66
     *
67
     * @param $widget object
68
     * @param array ...$args
69
     *
70
     * @return string
71
     */
72
    private function generateHtml($widget, ...$args)
73
    {
74
        // Everything inside this function is executed only when the cache is not available.
75 20
        $expensivePhpCode = function () use ($widget, $args) {
76 18
            $this->makeDataForView($widget, $args);
77
78 18
            return $this->renderTemplate($widget, ...$args);
0 ignored issues
show
Bug introduced by
$args is expanded, but the parameter $args of Imanghafoori\Widgets\Uti...derer::renderTemplate() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

78
            return $this->renderTemplate($widget, /** @scrutinizer ignore-type */ ...$args);
Loading history...
79 20
        };
80
81 20
        if (! $widget->cacheView) {
82 2
            return $expensivePhpCode();
83
        }
84
85
        // We first try to get the output from the cache before trying to run the expensive $expensivePhpCode...
86 19
        return resolve(Cache::class)->cacheResult($args, $expensivePhpCode, $widget);
0 ignored issues
show
Bug introduced by
Are you sure the usage of resolve(Imanghafoori\Wid...ensivePhpCode, $widget) targeting Imanghafoori\Widgets\Utils\Cache::cacheResult() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
87
    }
88
89
    /**
90
     * @param $widget object
91
     * @param $args array
92
     *
93
     * @return null
94
     */
95
    private function makeDataForView($widget, array $args)
96
    {
97 18
        $expensiveCode = function () use ($widget, $args) {
98 18
            $viewData = $this->callController($widget, $args);
99
100 18
            if ($widget->presenter) {
101
                // Pipe the data through the presenter before sending it to view.
102 1
                $viewData = \App::call($widget->presenter, [$viewData]);
103
            }
104
105 18
            return $viewData;
106 18
        };
107
108 18
        $this->_viewData = resolve(Cache::class)->cacheResult($args, $expensiveCode, $widget, 'dataProvider');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this->_viewData is correct as resolve(Imanghafoori\Wid...widget, 'dataProvider') targeting Imanghafoori\Widgets\Utils\Cache::cacheResult() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
109 18
    }
110
111
    /**
112
     * @param      $widget object
113
     * @param null $args
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $args is correct as it would always require null to be passed?
Loading history...
114
     *
115
     * @throws \Throwable
116
     * @return string HTML output
117
     */
118 18
    private function renderTemplate($widget, $args = null)
119
    {
120
        // Here we render the view file to raw html.
121 18
        $data = [$widget->contextAs => $this->_viewData, 'params' => $args];
122
123
        try {
124 18
            $this->html = view($widget->template, $data)->render();
125
        } catch (\Throwable $t) {
126
            throw new \ErrorException('There was some error rendering '.get_class($widget).', template file: \''.$widget->template.'\' Error: '.$t->getMessage());
127
        }
128
129
        // We try to minify the html before storing it in cache to save space.
130 18
        if ($this->_policies->widgetShouldBeMinified($widget)) {
131 9
            $this->html = resolve(HtmlMinifier::class)->minify($this->html);
132
        }
133
134
        // We add some HTML comments before and after the widget output
135
        // So then, we will be able to easily identify the widget in browser's developer tool.
136 18
        if ($this->_policies->widgetShouldHaveDebugInfo()) {
137 8
            $this->html = resolve(DebugInfo::class)->addIdentifierToHtml($widget, $this->html);
138
        }
139
140 18
        return $this->html;
141
    }
142
143 18
    private function callController($widget, array $args)
144
    {
145 18
        if (! isset($widget->controller)) {
146
            $viewData = [];
147 18
        } elseif (is_array($widget->controller) && is_string($widget->controller[0])) {
148
            $viewData = call_user_func_array($widget->controller, $args);
149
        } else {
150
            // Here we call the data method on the widget class.
151 18
            $viewData = \App::call($widget->controller, ...$args);
0 ignored issues
show
Bug introduced by
$args is expanded, but the parameter $parameters of Illuminate\Foundation\Application::call() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

151
            $viewData = \App::call($widget->controller, /** @scrutinizer ignore-type */ ...$args);
Loading history...
152
        }
153
154 18
        return $viewData;
155
    }
156
}
157