Passed
Push — master ( 5e116a...a23bd1 )
by Thomas
11:50 queued 09:28
created

DeferBackend::includeInHTML()   F

Complexity

Conditions 29
Paths > 20000

Size

Total Lines 131
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 3 Features 0
Metric Value
eloc 72
c 9
b 3
f 0
dl 0
loc 131
rs 0
cc 29
nc 245705
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace LeKoala\DeferBackend;
4
5
use Exception;
6
use SilverStripe\View\HTML;
7
use InvalidArgumentException;
8
use SilverStripe\Core\Config\Configurable;
9
use SilverStripe\View\SSViewer;
10
use SilverStripe\View\Requirements;
11
use SilverStripe\View\ThemeResourceLoader;
12
use SilverStripe\View\Requirements_Backend;
13
14
/**
15
 * A backend that defers everything by default
16
 *
17
 * Also insert custom head tags first because order may matter
18
 *
19
 * @link https://flaviocopes.com/javascript-async-defer/
20
 */
21
class DeferBackend extends Requirements_Backend
22
{
23
    use Configurable;
24
25
    /**
26
     * @config
27
     * @var boolean
28
     */
29
    private static $enable_js_modules = false;
30
31
    // It's better to write to the head with defer
32
    public $writeJavascriptToBody = false;
33
34
    /**
35
     * @return $this
36
     */
37
    public static function getDeferBackend()
38
    {
39
        $backend = Requirements::backend();
40
        if (!$backend instanceof self) {
41
            throw new Exception("Requirements backend is currently of class " . get_class($backend));
42
        }
43
        return $backend;
44
    }
45
46
    /**
47
     * @param Requirements_Backend $oldBackend defaults to current backend
48
     * @return $this
49
     */
50
    public static function replaceBackend(Requirements_Backend $oldBackend = null)
51
    {
52
        if ($oldBackend === null) {
53
            $oldBackend = Requirements::backend();
54
        }
55
        $deferBackend = new static;
56
        foreach ($oldBackend->getCSS() as $file => $opts) {
57
            $deferBackend->css($file, null, $opts);
58
        }
59
        foreach ($oldBackend->getJavascript() as $file => $opts) {
60
            $deferBackend->javascript($file, $opts);
61
        }
62
        foreach ($oldBackend->getCustomCSS() as $id => $script) {
63
            $deferBackend->customCSS($script, $id);
64
        }
65
        foreach ($oldBackend->getCustomScripts() as $id => $script) {
66
            $deferBackend->customScript($script, $id);
67
        }
68
        Requirements::set_backend($deferBackend);
69
        return $deferBackend;
70
    }
71
72
    /**
73
     * @return array
74
     */
75
    public static function listCookieTypes()
76
    {
77
        return ['strictly-necessary', 'functionality', 'tracking', 'targeting'];
78
    }
79
80
    /**
81
     * Register the given JavaScript file as required.
82
     *
83
     * @param string $file Either relative to docroot or in the form "vendor/package:resource"
84
     * @param array $options List of options. Available options include:
85
     * - 'provides' : List of scripts files included in this file
86
     * - 'async' : Boolean value to set async attribute to script tag
87
     * - 'defer' : Boolean value to set defer attribute to script tag (true by default)
88
     * - 'type' : Override script type= value.
89
     * - 'integrity' : SubResource Integrity hash
90
     * - 'crossorigin' : Cross-origin policy for the resource
91
     * - 'cookie-consent' : Type of cookie for conditionnal loading : strictly-necessary,functionality,tracking,targeting
92
     */
93
    public function javascript($file, $options = array())
94
    {
95
        if (!is_array($options)) {
0 ignored issues
show
introduced by
The condition is_array($options) is always true.
Loading history...
96
            $options = [];
97
        }
98
        if (self::config()->enable_js_modules) {
99
            if (empty($options['type']) && self::config()->enable_js_modules) {
100
                $options['type'] = 'module';
101
            }
102
            // Modules are deferred by default
103
            if (isset($options['defer']) && $options['type'] == "module") {
104
                unset($options['defer']);
105
            }
106
        } else {
107
            // We want to defer by default, but we can disable it if needed
108
            if (!isset($options['defer'])) {
109
                $options['defer'] = true;
110
            }
111
        }
112
        if (isset($options['cookie-consent'])) {
113
            if (!in_array($options['cookie-consent'], self::listCookieTypes())) {
114
                throw new InvalidArgumentException("The cookie-consent value is invalid, it must be one of: strictly-necessary,functionality,tracking,targeting");
115
            }
116
            // switch to text plain for conditional loading
117
            $options['type'] = 'text/plain';
118
        }
119
        parent::javascript($file, $options);
120
        if (isset($options['cookie-consent'])) {
121
            $this->javascript[$file]['cookie-consent'] = $options['cookie-consent'];
122
        }
123
    }
124
125
    /**
126
     * @param string $name
127
     * @param string|array $type Pass the type or an array of options
128
     * @return void
129
     */
130
    public function themedJavascript($name, $type = null)
131
    {
132
        if ($type !== null && (!is_string($type) && !is_array($type))) {
0 ignored issues
show
introduced by
The condition is_array($type) is always true.
Loading history...
133
            throw new InvalidArgumentException("Type must be a string or an array");
134
        }
135
        $path = ThemeResourceLoader::inst()->findThemedJavascript($name, SSViewer::get_themes());
136
        if ($path) {
137
            $options = [];
138
            if ($type) {
139
                if (is_string($type)) {
140
                    $options['type'] = $type;
141
                } else {
142
                    $options = $type;
143
                }
144
            }
145
            $this->javascript($path, $options);
146
        } else {
147
            throw new InvalidArgumentException(
148
                "The javascript file doesn't exist. Please check if the file $name.js exists in any "
149
                    . "context or search for themedJavascript references calling this file in your templates."
150
            );
151
        }
152
    }
153
154
    /**
155
     * Get all css files
156
     *
157
     * @return array
158
     */
159
    public function getCSS()
160
    {
161
        $css = array_diff_key($this->css, $this->blocked);
162
        // Theme and assets files should always come last to have a proper cascade
163
        $allCss = [];
164
        $themeCss = [];
165
        foreach ($css as $file => $arr) {
166
            if (strpos($file, 'themes') === 0 || strpos($file, '/assets') === 0) {
167
                $themeCss[$file] = $arr;
168
            } else {
169
                $allCss[$file] = $arr;
170
            }
171
        }
172
        return array_merge($allCss, $themeCss);
173
    }
174
175
    /**
176
     * Update the given HTML content with the appropriate include tags for the registered
177
     * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
178
     * including a head and body tag.
179
     *
180
     * @param string $content HTML content that has already been parsed from the $templateFile through {@link SSViewer}
181
     * @return string HTML content augmented with the requirements tags
182
     */
183
    public function includeInHTML($content)
184
    {
185
        // Get our CSP nonce, it's always good to have even if we don't use it :-)
186
        $nonce = CspProvider::getCspNonce();
187
188
        // Skip if content isn't injectable, or there is nothing to inject
189
        $tagsAvailable = preg_match('#</head\b#', $content);
190
        $hasFiles = !empty($this->css)
191
            || !empty($this->javascript)
192
            || !empty($this->customCSS)
193
            || !empty($this->customScript)
194
            || !empty($this->customHeadTags);
195
196
        if (!$tagsAvailable || !$hasFiles) {
197
            return $content;
198
        }
199
        $requirements = '';
200
        $jsRequirements = '';
201
202
        // Combine files - updates $this->javascript and $this->css
203
        $this->processCombinedFiles();
204
205
        // Script tags for js links
206
        foreach ($this->getJavascript() as $file => $attributes) {
207
            // Build html attributes
208
            $htmlAttributes = [
209
                'type' => isset($attributes['type']) ? $attributes['type'] : "application/javascript",
210
                'src' => $this->pathForFile($file),
211
                'nonce' => $nonce,
212
            ];
213
            if (!empty($attributes['async'])) {
214
                $htmlAttributes['async'] = 'async';
215
            }
216
            // defer is not allowed for module, ignore it as it does the same anyway
217
            if (!empty($attributes['defer']) && $htmlAttributes['type'] !== 'module') {
218
                $htmlAttributes['defer'] = 'defer';
219
            }
220
            if (!empty($attributes['integrity'])) {
221
                $htmlAttributes['integrity'] = $attributes['integrity'];
222
            }
223
            if (!empty($attributes['crossorigin'])) {
224
                $htmlAttributes['crossorigin'] = $attributes['crossorigin'];
225
            }
226
            if (!empty($attributes['cookie-consent'])) {
227
                $htmlAttributes['cookie-consent'] = $attributes['cookie-consent'];
228
            }
229
            $jsRequirements .= str_replace(' />', '>', HTML::createTag('script', $htmlAttributes));
230
            $jsRequirements .= "\n";
231
        }
232
233
        // Add all inline JavaScript *after* including external files they might rely on
234
        foreach ($this->getCustomScripts() as $scriptId => $script) {
235
            $type = self::config()->enable_js_modules ? 'module' : 'application/javascript';
236
            $attributes = [
237
                'type' => $type,
238
                'nonce' => $nonce,
239
            ];
240
241
            // since the Requirements API does not support passing variables, we use naming conventions
242
            if ($scriptId) {
243
                // Check for jsmodule in the name, since we have no other way to pass arguments
244
                if (strpos($scriptId, "jsmodule") !== false) {
245
                    $attributes['type'] = 'module';
246
                }
247
248
                // For cookie-consent, we rely on last part of uniquness id
249
                $parts = explode("-", $scriptId);
250
                $lastPart = array_pop($parts);
251
                if (in_array($lastPart, self::listCookieTypes())) {
252
                    $attributes['type'] = 'text/plain';
253
                    $attributes['cookie-consent'] = $lastPart;
254
                }
255
            }
256
257
            // Wrap script in a DOMContentLoaded
258
            // Make sure we don't add the eventListener twice (this will only work for simple scripts)
259
            // Make sure we don't wrap scripts concerned by security policies
260
            // Js modules are deferred by default, even if they are inlined, so not wrapping needed
261
            // @link https://stackoverflow.com/questions/41394983/how-to-defer-inline-javascript
262
            if (empty($attributes['cookie-consent']) && strpos($script, 'window.addEventListener') === false && $attributes['type'] !== 'module') {
263
                $script = "window.addEventListener('DOMContentLoaded', function() { $script });";
264
            }
265
266
            // Remove comments if any
267
            $script = preg_replace('/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/', '', $script);
268
269
            $jsRequirements .= HTML::createTag(
270
                'script',
271
                $attributes,
272
                "//<![CDATA[\n{$script}\n//]]>"
273
            );
274
            $jsRequirements .= "\n";
275
        }
276
277
        // Custom head tags (comes first)
278
        foreach ($this->getCustomHeadTags() as $customHeadTag) {
279
            $requirements .= "{$customHeadTag}\n";
280
        }
281
282
        // CSS file links
283
        foreach ($this->getCSS() as $file => $params) {
284
            $htmlAttributes = [
285
                'rel' => 'stylesheet',
286
                'type' => 'text/css',
287
                'href' => $this->pathForFile($file),
288
            ];
289
            if (!empty($params['media'])) {
290
                $htmlAttributes['media'] = $params['media'];
291
            }
292
            $requirements .= str_replace(' />', '>', HTML::createTag('link', $htmlAttributes));
293
            $requirements .= "\n";
294
        }
295
296
        // Literal custom CSS content
297
        foreach ($this->getCustomCSS() as $css) {
298
            $requirements .= HTML::createTag('style', ['type' => 'text/css'], "\n{$css}\n");
299
            $requirements .= "\n";
300
        }
301
302
        // Inject CSS  into body
303
        $content = $this->insertTagsIntoHead($requirements, $content);
304
305
        // Inject scripts
306
        if ($this->getForceJSToBottom()) {
307
            $content = $this->insertScriptsAtBottom($jsRequirements, $content);
308
        } elseif ($this->getWriteJavascriptToBody()) {
309
            $content = $this->insertScriptsIntoBody($jsRequirements, $content);
310
        } else {
311
            $content = $this->insertTagsIntoHead($jsRequirements, $content);
312
        }
313
        return $content;
314
    }
315
}
316