Completed
Push — master ( 1537c0...f6919b )
by Song
02:34
created

HasAssets   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 397
Duplicated Lines 12.09 %

Coupling/Cohesion

Components 3
Dependencies 1

Importance

Changes 0
Metric Value
dl 48
loc 397
rs 8.4
c 0
b 0
f 0
wmc 50
lcom 3
cbo 1

14 Methods

Rating   Name   Duplication   Size   Complexity  
A css() 16 16 3
A baseCss() 0 14 2
A js() 16 16 3
A headerJs() 0 8 2
A baseJs() 0 10 2
A ignoreMinify() 0 6 2
A script() 0 23 3
A style() 0 14 2
A html() 0 8 2
A getManifestData() 0 13 2
A getMinifiedCss() 8 8 3
A getMinifiedJs() 8 8 3
A jQuery() 0 4 1
D component() 0 66 20

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like HasAssets often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use HasAssets, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Encore\Admin\Traits;
4
5
trait HasAssets
6
{
7
    /**
8
     * @var array
9
     */
10
    public static $script = [];
11
12
    /**
13
     * @var array
14
     */
15
    public static $deferredScript = [];
16
17
    /**
18
     * @var array
19
     */
20
    public static $style = [];
21
22
    /**
23
     * @var array
24
     */
25
    public static $css = [];
26
27
    /**
28
     * @var array
29
     */
30
    public static $js = [];
31
32
    /**
33
     * @var array
34
     */
35
    public static $html = [];
36
37
    /**
38
     * @var array
39
     */
40
    public static $headerJs = [];
41
42
    /**
43
     * @var string
44
     */
45
    public static $manifest = 'vendor/laravel-admin/minify-manifest.json';
46
47
    /**
48
     * @var array
49
     */
50
    public static $manifestData = [];
51
52
    /**
53
     * @var array
54
     */
55
    public static $min = [
56
        'js'  => 'vendor/laravel-admin/laravel-admin.min.js',
57
        'css' => 'vendor/laravel-admin/laravel-admin.min.css',
58
    ];
59
60
    /**
61
     * @var array
62
     */
63
    public static $baseCss = [
64
        'vendor/laravel-admin/AdminLTE/bootstrap/css/bootstrap.min.css',
65
        'vendor/laravel-admin/font-awesome/css/font-awesome.min.css',
66
        'vendor/laravel-admin/laravel-admin/laravel-admin.css',
67
        'vendor/laravel-admin/nprogress/nprogress.css',
68
        'vendor/laravel-admin/sweetalert2/dist/sweetalert2.css',
69
        'vendor/laravel-admin/nestable/nestable.css',
70
        'vendor/laravel-admin/toastr/build/toastr.min.css',
71
        'vendor/laravel-admin/bootstrap3-editable/css/bootstrap-editable.css',
72
        'vendor/laravel-admin/google-fonts/fonts.css',
73
        'vendor/laravel-admin/AdminLTE/dist/css/AdminLTE.min.css',
74
    ];
75
76
    /**
77
     * @var array
78
     */
79
    public static $baseJs = [
80
        'vendor/laravel-admin/AdminLTE/bootstrap/js/bootstrap.min.js',
81
        'vendor/laravel-admin/AdminLTE/plugins/slimScroll/jquery.slimscroll.min.js',
82
        'vendor/laravel-admin/AdminLTE/dist/js/app.min.js',
83
        'vendor/laravel-admin/jquery-pjax/jquery.pjax.js',
84
        'vendor/laravel-admin/nprogress/nprogress.js',
85
        'vendor/laravel-admin/nestable/jquery.nestable.js',
86
        'vendor/laravel-admin/toastr/build/toastr.min.js',
87
        'vendor/laravel-admin/bootstrap3-editable/js/bootstrap-editable.min.js',
88
        'vendor/laravel-admin/sweetalert2/dist/sweetalert2.min.js',
89
        'vendor/laravel-admin/laravel-admin/laravel-admin.js',
90
    ];
91
92
    /**
93
     * @var string
94
     */
95
    public static $jQuery = 'vendor/laravel-admin/AdminLTE/plugins/jQuery/jQuery-2.1.4.min.js';
96
97
    /**
98
     * @var array
99
     */
100
    public static $minifyIgnores = [];
101
102
    /**
103
     * Add css or get all css.
104
     *
105
     * @param null $css
106
     * @param bool $minify
107
     *
108
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
109
     */
110 View Code Duplication
    public static function css($css = null, $minify = true)
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...
111
    {
112
        static::ignoreMinify($css, $minify);
113
114
        if (!is_null($css)) {
115
            return self::$css = array_merge(self::$css, (array) $css);
116
        }
117
118
        if (!$css = static::getMinifiedCss()) {
119
            $css = array_merge(static::$css, static::baseCss());
120
        }
121
122
        $css = array_filter(array_unique($css));
123
124
        return view('admin::partials.css', compact('css'));
125
    }
126
127
    /**
128
     * @param null $css
129
     * @param bool $minify
130
     *
131
     * @return array|null
132
     */
133
    public static function baseCss($css = null, $minify = true)
134
    {
135
        static::ignoreMinify($css, $minify);
136
137
        if (!is_null($css)) {
138
            return static::$baseCss = $css;
139
        }
140
141
        $skin = config('admin.skin', 'skin-blue-light');
142
143
        array_unshift(static::$baseCss, "vendor/laravel-admin/AdminLTE/dist/css/skins/{$skin}.min.css");
144
145
        return static::$baseCss;
146
    }
147
148
    /**
149
     * Add js or get all js.
150
     *
151
     * @param null $js
152
     * @param bool $minify
153
     *
154
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
155
     */
156 View Code Duplication
    public static function js($js = null, $minify = true)
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...
157
    {
158
        static::ignoreMinify($js, $minify);
159
160
        if (!is_null($js)) {
161
            return self::$js = array_merge(self::$js, (array) $js);
162
        }
163
164
        if (!$js = static::getMinifiedJs()) {
165
            $js = array_merge(static::baseJs(), static::$js);
166
        }
167
168
        $js = array_filter(array_unique($js));
169
170
        return view('admin::partials.js', compact('js'));
171
    }
172
173
    /**
174
     * Add js or get all js.
175
     *
176
     * @param null $js
177
     *
178
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
179
     */
180
    public static function headerJs($js = null)
181
    {
182
        if (!is_null($js)) {
183
            return self::$headerJs = array_merge(self::$headerJs, (array) $js);
184
        }
185
186
        return view('admin::partials.js', ['js' => array_unique(static::$headerJs)]);
187
    }
188
189
    /**
190
     * @param null $js
191
     * @param bool $minify
192
     *
193
     * @return array|null
194
     */
195
    public static function baseJs($js = null, $minify = true)
196
    {
197
        static::ignoreMinify($js, $minify);
198
199
        if (!is_null($js)) {
200
            return static::$baseJs = $js;
201
        }
202
203
        return static::$baseJs;
204
    }
205
206
    /**
207
     * @param string $assets
208
     * @param bool   $ignore
209
     */
210
    public static function ignoreMinify($assets, $ignore = true)
211
    {
212
        if (!$ignore) {
213
            static::$minifyIgnores[] = $assets;
214
        }
215
    }
216
217
    /**
218
     * @param string $script
219
     * @param bool   $deferred
220
     *
221
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
222
     */
223
    public static function script($script = '', $deferred = false)
224
    {
225
        if (!empty($script)) {
226
            if ($deferred) {
227
                return self::$deferredScript = array_merge(self::$deferredScript, (array) $script);
228
            }
229
230
            return self::$script = array_merge(self::$script, (array) $script);
231
        }
232
233
        $script = collect(static::$script)
234
            ->merge(static::$deferredScript)
235
            ->unique()
236
            ->map(function ($line) {return $line;
237
                //@see https://stackoverflow.com/questions/19509863/how-to-remove-js-comments-using-php
238
                $pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\')\/\/.*))/';
0 ignored issues
show
Unused Code introduced by
$pattern = '/(?:(?:\\/\\...:|\\\\|\')\\/\\/.*))/'; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
239
                $line = preg_replace($pattern, '', $line);
240
241
                return preg_replace('/\s+/', ' ', $line);
242
            });
243
244
        return view('admin::partials.script', compact('script'));
245
    }
246
247
    /**
248
     * @param string $style
249
     *
250
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
251
     */
252
    public static function style($style = '')
253
    {
254
        if (!empty($style)) {
255
            return self::$style = array_merge(self::$style, (array) $style);
256
        }
257
258
        $style = collect(static::$style)
259
            ->unique()
260
            ->map(function ($line) {
261
                return preg_replace('/\s+/', ' ', $line);
262
            });
263
264
        return view('admin::partials.style', compact('style'));
265
    }
266
267
    /**
268
     * @param string $html
269
     *
270
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
271
     */
272
    public static function html($html = '')
273
    {
274
        if (!empty($html)) {
275
            return self::$html = array_merge(self::$html, (array) $html);
276
        }
277
278
        return view('admin::partials.html', ['html' => array_unique(self::$html)]);
279
    }
280
281
    /**
282
     * @param string $key
283
     *
284
     * @return mixed
285
     */
286
    protected static function getManifestData($key)
287
    {
288
        if (!empty(static::$manifestData)) {
289
            return static::$manifestData[$key];
290
        }
291
292
        static::$manifestData = json_decode(
293
            file_get_contents(public_path(static::$manifest)),
294
            true
295
        );
296
297
        return static::$manifestData[$key];
298
    }
299
300
    /**
301
     * @return bool|mixed
302
     */
303 View Code Duplication
    protected static function getMinifiedCss()
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...
304
    {
305
        if (!config('admin.minify_assets') || !file_exists(public_path(static::$manifest))) {
306
            return false;
307
        }
308
309
        return static::getManifestData('css');
310
    }
311
312
    /**
313
     * @return bool|mixed
314
     */
315 View Code Duplication
    protected static function getMinifiedJs()
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...
316
    {
317
        if (!config('admin.minify_assets') || !file_exists(public_path(static::$manifest))) {
318
            return false;
319
        }
320
321
        return static::getManifestData('js');
322
    }
323
324
    /**
325
     * @return string
326
     */
327
    public function jQuery()
328
    {
329
        return admin_asset(static::$jQuery);
330
    }
331
332
    /**
333
     * @param $component
334
     */
335
    public static function component($component, $data = [])
336
    {
337
        $string = view($component, $data)->render();
0 ignored issues
show
Bug introduced by
The method render does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
338
339
        $dom = new \DOMDocument();
340
341
        libxml_use_internal_errors(true);
342
        $dom->loadHTML('<?xml encoding="utf-8" ?>' . $string);
343
        libxml_use_internal_errors(false);
344
345
        if ($head = $dom->getElementsByTagName('head')->item(0)) {
346
            foreach ($head->childNodes as $child) {
347
                if ($child instanceof \DOMElement) {
348
                    if ($child->tagName == 'style' && !empty($child->nodeValue)) {
349
                        static::style($child->nodeValue);
350
                        continue;
351
                    }
352
353
                    if ($child->tagName == 'link' && $child->hasAttribute('href')) {
354
                        static::css($child->getAttribute('href'));
355
                    }
356
357
                    if ($child->tagName == 'script') {
358
                        if ($child->hasAttribute('src')) {
359
                            static::js($child->getAttribute('src'));
360
                        } else {
361
                            static::script(';(function () {'.$child->nodeValue.'})();');
362
                        }
363
364
                        continue;
365
                    }
366
                }
367
            }
368
        }
369
370
        $render = '';
371
372
        if($body = $dom->getElementsByTagName('body')->item(0)) {
373
            foreach ($body->childNodes as $child) {
374
                if ($child instanceof \DOMElement) {
375
                    if ($child->tagName == 'style' && !empty($child->nodeValue)) {
376
                        static::style($child->nodeValue);
377
                        continue;
378
                    }
379
380
                    if ($child->tagName == 'script' && !empty($child->nodeValue)) {
381
                        static::script(';(function () {' . $child->nodeValue . '})();');
382
                        continue;
383
                    }
384
385
                    if ($child->tagName == 'template') {
386
                        $html = '';
387
                        foreach ($child->childNodes as $childNode) {
388
                            $html .= $child->ownerDocument->saveHTML($childNode);
389
                        }
390
                        $html && static::html($html);
391
                        continue;
392
                    }
393
                }
394
395
                $render .= $body->ownerDocument->saveHTML($child);
396
            }
397
        }
398
399
        return trim($render);
400
    }
401
}
402