Passed
Push — master ( a6857c...74ff06 )
by Thomas
01:42
created

DeferBackend   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 242
Duplicated Lines 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 45
eloc 108
c 4
b 1
f 0
dl 0
loc 242
rs 8.8

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getCSS() 0 14 4
A javascript() 0 16 5
A replaceBackend() 0 20 6
A getDeferBackend() 0 7 2
A themedJavascript() 0 17 5
A customScript() 0 13 2
F includeInHTML() 0 94 21

How to fix   Complexity   

Complex Class

Complex classes like DeferBackend 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.

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 DeferBackend, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace LeKoala\DeferBackend;
4
5
use Exception;
6
use SilverStripe\View\HTML;
7
use InvalidArgumentException;
8
use SilverStripe\View\SSViewer;
9
use SilverStripe\View\Requirements;
10
use SilverStripe\View\ThemeResourceLoader;
11
use SilverStripe\View\Requirements_Backend;
12
13
/**
14
 * A backend that defers everything by default
15
 *
16
 * Also insert custom head tags first because order may matter
17
 *
18
 * @link https://flaviocopes.com/javascript-async-defer/
19
 */
20
class DeferBackend extends Requirements_Backend
21
{
22
    // It's better to write to the head with defer
23
    public $writeJavascriptToBody = false;
24
25
    /**
26
     * @return $this
27
     */
28
    public static function getDeferBackend()
29
    {
30
        $backend = Requirements::backend();
31
        if (!$backend instanceof self) {
32
            throw new Exception("Requirements backend is currently of class " . get_class($backend));
33
        }
34
        return $backend;
35
    }
36
37
    /**
38
     * @param Requirements_Backend $oldBackend defaults to current backend
39
     * @return $this
40
     */
41
    public static function replaceBackend(Requirements_Backend $oldBackend = null)
42
    {
43
        if ($oldBackend === null) {
44
            $oldBackend = Requirements::backend();
45
        }
46
        $deferBackend = new static;
47
        foreach ($oldBackend->getCSS() as $file => $opts) {
48
            $deferBackend->css($file, null, $opts);
49
        }
50
        foreach ($oldBackend->getJavascript() as $file => $opts) {
51
            $deferBackend->javascript($file, null, $opts);
0 ignored issues
show
Unused Code introduced by
The call to LeKoala\DeferBackend\DeferBackend::javascript() has too many arguments starting with $opts. ( Ignorable by Annotation )

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

51
            $deferBackend->/** @scrutinizer ignore-call */ 
52
                           javascript($file, null, $opts);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
52
        }
53
        foreach ($oldBackend->getCustomCSS() as $id => $script) {
54
            $deferBackend->customCSS($script, $id);
55
        }
56
        foreach ($oldBackend->getCustomScripts() as $id => $script) {
57
            $deferBackend->customScript($script, $id);
58
        }
59
        Requirements::set_backend($deferBackend);
60
        return $deferBackend;
61
    }
62
63
    /**
64
     * Register the given JavaScript file as required.
65
     *
66
     * @param string $file Either relative to docroot or in the form "vendor/package:resource"
67
     * @param array $options List of options. Available options include:
68
     * - 'provides' : List of scripts files included in this file
69
     * - 'async' : Boolean value to set async attribute to script tag
70
     * - 'defer' : Boolean value to set defer attribute to script tag (true by default)
71
     * - 'type' : Override script type= value.
72
     * - 'integrity' : SubResource Integrity hash
73
     * - 'crossorigin' : Cross-origin policy for the resource
74
     * - 'cookie-consent' : Type of cookie for conditionnal loading : strictly-necessary,functionality,tracking,targeting
75
     */
76
    public function javascript($file, $options = array())
77
    {
78
        // We want to defer by default, but we can disable it if needed
79
        if (!isset($options['defer'])) {
80
            $options['defer'] = true;
81
        }
82
        if (isset($options['cookie-consent'])) {
83
            if (!in_array($options['cookie-consent'], ['strictly-necessary', 'functionality', 'tracking', 'targeting'])) {
84
                throw new InvalidArgumentException("The cookie-consent value is invalid, it must be one of: strictly-necessary,functionality,tracking,targeting");
85
            }
86
            // switch to text plain for conditional loading
87
            $options['type'] = 'text/plain';
88
        }
89
        parent::javascript($file, $options);
90
        if (isset($options['cookie-consent'])) {
91
            $this->javascript[$file]['cookie-consent'] = $options['cookie-consent'];
92
        }
93
    }
94
95
    /**
96
     * @param string $name
97
     * @param string|array $type Pass the type or an array of options
98
     * @return void
99
     */
100
    public function themedJavascript($name, $type = null)
101
    {
102
        $path = ThemeResourceLoader::inst()->findThemedJavascript($name, SSViewer::get_themes());
103
        if ($path) {
104
            $opts = [];
105
            if ($type) {
106
                if (is_string($type)) {
107
                    $opts['type'] = $type;
108
                } elseif (is_array($type)) {
0 ignored issues
show
introduced by
The condition is_array($type) is always true.
Loading history...
109
                    $opts = $type;
110
                }
111
            }
112
            $this->javascript($path, $opts);
113
        } else {
114
            throw new InvalidArgumentException(
115
                "The javascript file doesn't exist. Please check if the file $name.js exists in any "
116
                    . "context or search for themedJavascript references calling this file in your templates."
117
            );
118
        }
119
    }
120
121
    /**
122
     * @inheritDoc
123
     */
124
    public function customScript($script, $uniquenessID = null)
125
    {
126
        // Wrap script in a DOMContentLoaded
127
        // Make sure we don't add the eventListener twice (this will only work for simple scripts)
128
        // @link https://stackoverflow.com/questions/41394983/how-to-defer-inline-javascript
129
        if (strpos($script, 'window.addEventListener') === false) {
130
            $script = "window.addEventListener('DOMContentLoaded', function() { $script });";
131
        }
132
133
        // Remove comments if any
134
        $script = preg_replace('/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/', '', $script);
135
136
        return parent::customScript($script, $uniquenessID);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::customScript($script, $uniquenessID) targeting SilverStripe\View\Requir...Backend::customScript() 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...
137
    }
138
139
    /**
140
     * Get all css files
141
     *
142
     * @return array
143
     */
144
    public function getCSS()
145
    {
146
        $css = array_diff_key($this->css, $this->blocked);
147
        // Theme and assets files should always come last to have a proper cascade
148
        $allCss = [];
149
        $themeCss = [];
150
        foreach ($css as $file => $arr) {
151
            if (strpos($file, 'themes') === 0 || strpos($file, '/assets') === 0) {
152
                $themeCss[$file] = $arr;
153
            } else {
154
                $allCss[$file] = $arr;
155
            }
156
        }
157
        return array_merge($allCss, $themeCss);
158
    }
159
160
    /**
161
     * Update the given HTML content with the appropriate include tags for the registered
162
     * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
163
     * including a head and body tag.
164
     *
165
     * @param string $content HTML content that has already been parsed from the $templateFile through {@link SSViewer}
166
     * @return string HTML content augmented with the requirements tags
167
     */
168
    public function includeInHTML($content)
169
    {
170
        // Get our CSP nonce, it's always good to have even if we don't use it :-)
171
        $nonce = CspProvider::getCspNonce();
172
173
        // Skip if content isn't injectable, or there is nothing to inject
174
        $tagsAvailable = preg_match('#</head\b#', $content);
175
        $hasFiles = $this->css || $this->javascript || $this->customCSS || $this->customScript || $this->customHeadTags;
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->css of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Bug Best Practice introduced by
The expression $this->javascript of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Bug Best Practice introduced by
The expression $this->customCSS of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Bug Best Practice introduced by
The expression $this->customHeadTags of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Bug Best Practice introduced by
The expression $this->customScript of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
176
        if (!$tagsAvailable || !$hasFiles) {
177
            return $content;
178
        }
179
        $requirements = '';
180
        $jsRequirements = '';
181
182
        // Combine files - updates $this->javascript and $this->css
183
        $this->processCombinedFiles();
184
185
        // Script tags for js links
186
        foreach ($this->getJavascript() as $file => $attributes) {
187
            // Build html attributes
188
            $htmlAttributes = [
189
                'type' => isset($attributes['type']) ? $attributes['type'] : "application/javascript",
190
                'src' => $this->pathForFile($file),
191
                'nonce' => $nonce,
192
            ];
193
            if (!empty($attributes['async'])) {
194
                $htmlAttributes['async'] = 'async';
195
            }
196
            if (!empty($attributes['defer'])) {
197
                $htmlAttributes['defer'] = 'defer';
198
            }
199
            if (!empty($attributes['integrity'])) {
200
                $htmlAttributes['integrity'] = $attributes['integrity'];
201
            }
202
            if (!empty($attributes['crossorigin'])) {
203
                $htmlAttributes['crossorigin'] = $attributes['crossorigin'];
204
            }
205
            if (!empty($attributes['cookie-consent'])) {
206
                $htmlAttributes['cookie-consent'] = $attributes['cookie-consent'];
207
            }
208
            $jsRequirements .= HTML::createTag('script', $attributes);
209
            $jsRequirements .= "\n";
210
        }
211
212
        // Add all inline JavaScript *after* including external files they might rely on
213
        foreach ($this->getCustomScripts() as $script) {
214
            $jsRequirements .= HTML::createTag(
215
                'script',
216
                [
217
                    'type' => 'application/javascript',
218
                    'nonce' => $nonce,
219
                ],
220
                "//<![CDATA[\n{$script}\n//]]>"
221
            );
222
            $jsRequirements .= "\n";
223
        }
224
225
        // Custom head tags (comes first)
226
        foreach ($this->getCustomHeadTags() as $customHeadTag) {
227
            $requirements .= "{$customHeadTag}\n";
228
        }
229
230
        // CSS file links
231
        foreach ($this->getCSS() as $file => $params) {
232
            $htmlAttributes = [
233
                'rel' => 'stylesheet',
234
                'type' => 'text/css',
235
                'href' => $this->pathForFile($file),
236
            ];
237
            if (!empty($params['media'])) {
238
                $htmlAttributes['media'] = $params['media'];
239
            }
240
            $requirements .= HTML::createTag('link', $htmlAttributes);
241
            $requirements .= "\n";
242
        }
243
244
        // Literal custom CSS content
245
        foreach ($this->getCustomCSS() as $css) {
246
            $requirements .= HTML::createTag('style', ['type' => 'text/css'], "\n{$css}\n");
247
            $requirements .= "\n";
248
        }
249
250
        // Inject CSS  into body
251
        $content = $this->insertTagsIntoHead($requirements, $content);
252
253
        // Inject scripts
254
        if ($this->getForceJSToBottom()) {
255
            $content = $this->insertScriptsAtBottom($jsRequirements, $content);
256
        } elseif ($this->getWriteJavascriptToBody()) {
257
            $content = $this->insertScriptsIntoBody($jsRequirements, $content);
258
        } else {
259
            $content = $this->insertTagsIntoHead($jsRequirements, $content);
260
        }
261
        return $content;
262
    }
263
}
264