Passed
Push — master ( b99b02...a7e540 )
by Thomas
02:28
created

DeferBackend::customScript()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 13
rs 10
cc 2
nc 2
nop 2
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
     * @return array
65
     */
66
    public static function listCookieTypes()
67
    {
68
        return ['strictly-necessary', 'functionality', 'tracking', 'targeting'];
69
    }
70
71
    /**
72
     * Register the given JavaScript file as required.
73
     *
74
     * @param string $file Either relative to docroot or in the form "vendor/package:resource"
75
     * @param array $options List of options. Available options include:
76
     * - 'provides' : List of scripts files included in this file
77
     * - 'async' : Boolean value to set async attribute to script tag
78
     * - 'defer' : Boolean value to set defer attribute to script tag (true by default)
79
     * - 'type' : Override script type= value.
80
     * - 'integrity' : SubResource Integrity hash
81
     * - 'crossorigin' : Cross-origin policy for the resource
82
     * - 'cookie-consent' : Type of cookie for conditionnal loading : strictly-necessary,functionality,tracking,targeting
83
     */
84
    public function javascript($file, $options = array())
85
    {
86
        // We want to defer by default, but we can disable it if needed
87
        if (!isset($options['defer'])) {
88
            $options['defer'] = true;
89
        }
90
        if (isset($options['cookie-consent'])) {
91
            if (!in_array($options['cookie-consent'], self::listCookieTypes())) {
92
                throw new InvalidArgumentException("The cookie-consent value is invalid, it must be one of: strictly-necessary,functionality,tracking,targeting");
93
            }
94
            // switch to text plain for conditional loading
95
            $options['type'] = 'text/plain';
96
        }
97
        parent::javascript($file, $options);
98
        if (isset($options['cookie-consent'])) {
99
            $this->javascript[$file]['cookie-consent'] = $options['cookie-consent'];
100
        }
101
    }
102
103
    /**
104
     * @param string $name
105
     * @param string|array $type Pass the type or an array of options
106
     * @return void
107
     */
108
    public function themedJavascript($name, $type = null)
109
    {
110
        $path = ThemeResourceLoader::inst()->findThemedJavascript($name, SSViewer::get_themes());
111
        if ($path) {
112
            $opts = [];
113
            if ($type) {
114
                if (is_string($type)) {
115
                    $opts['type'] = $type;
116
                } elseif (is_array($type)) {
0 ignored issues
show
introduced by
The condition is_array($type) is always true.
Loading history...
117
                    $opts = $type;
118
                }
119
            }
120
            $this->javascript($path, $opts);
121
        } else {
122
            throw new InvalidArgumentException(
123
                "The javascript file doesn't exist. Please check if the file $name.js exists in any "
124
                    . "context or search for themedJavascript references calling this file in your templates."
125
            );
126
        }
127
    }
128
129
    /**
130
     * Get all css files
131
     *
132
     * @return array
133
     */
134
    public function getCSS()
135
    {
136
        $css = array_diff_key($this->css, $this->blocked);
137
        // Theme and assets files should always come last to have a proper cascade
138
        $allCss = [];
139
        $themeCss = [];
140
        foreach ($css as $file => $arr) {
141
            if (strpos($file, 'themes') === 0 || strpos($file, '/assets') === 0) {
142
                $themeCss[$file] = $arr;
143
            } else {
144
                $allCss[$file] = $arr;
145
            }
146
        }
147
        return array_merge($allCss, $themeCss);
148
    }
149
150
    /**
151
     * Update the given HTML content with the appropriate include tags for the registered
152
     * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
153
     * including a head and body tag.
154
     *
155
     * @param string $content HTML content that has already been parsed from the $templateFile through {@link SSViewer}
156
     * @return string HTML content augmented with the requirements tags
157
     */
158
    public function includeInHTML($content)
159
    {
160
        // Get our CSP nonce, it's always good to have even if we don't use it :-)
161
        $nonce = CspProvider::getCspNonce();
162
163
        // Skip if content isn't injectable, or there is nothing to inject
164
        $tagsAvailable = preg_match('#</head\b#', $content);
165
        $hasFiles = $this->css || $this->javascript || $this->customCSS || $this->customScript || $this->customHeadTags;
0 ignored issues
show
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->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->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...
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->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...
166
        if (!$tagsAvailable || !$hasFiles) {
167
            return $content;
168
        }
169
        $requirements = '';
170
        $jsRequirements = '';
171
172
        // Combine files - updates $this->javascript and $this->css
173
        $this->processCombinedFiles();
174
175
        // Script tags for js links
176
        foreach ($this->getJavascript() as $file => $attributes) {
177
            // Build html attributes
178
            $htmlAttributes = [
179
                'type' => isset($attributes['type']) ? $attributes['type'] : "application/javascript",
180
                'src' => $this->pathForFile($file),
181
                'nonce' => $nonce,
182
            ];
183
            if (!empty($attributes['async'])) {
184
                $htmlAttributes['async'] = 'async';
185
            }
186
            if (!empty($attributes['defer'])) {
187
                $htmlAttributes['defer'] = 'defer';
188
            }
189
            if (!empty($attributes['integrity'])) {
190
                $htmlAttributes['integrity'] = $attributes['integrity'];
191
            }
192
            if (!empty($attributes['crossorigin'])) {
193
                $htmlAttributes['crossorigin'] = $attributes['crossorigin'];
194
            }
195
            if (!empty($attributes['cookie-consent'])) {
196
                $htmlAttributes['cookie-consent'] = $attributes['cookie-consent'];
197
            }
198
            $jsRequirements .= HTML::createTag('script', $htmlAttributes);
199
            $jsRequirements .= "\n";
200
        }
201
202
        // Add all inline JavaScript *after* including external files they might rely on
203
        foreach ($this->getCustomScripts() as $scriptId => $script) {
204
            if (is_numeric($scriptId)) {
205
                $script = $scriptId;
206
                $scriptId = null;
207
            }
208
            $attributes = [
209
                'type' => 'application/javascript',
210
                'nonce' => $nonce,
211
            ];
212
            // For cookie-consent, since the Requirements API does not support passing variables
213
            // we rely on last part of uniquness id
214
            if ($scriptId) {
215
                $parts = explode("-", $scriptId);
216
                $lastPart = array_pop($parts);
217
                if (in_array($lastPart, self::listCookieTypes())) {
218
                    $attributes['type'] = 'text/plain';
219
                    $attributes['cookie-consent'] = $lastPart;
220
                }
221
            }
222
223
            // Wrap script in a DOMContentLoaded
224
            // Make sure we don't add the eventListener twice (this will only work for simple scripts)
225
            // Make sure we don't wrap scripts concerned by security policies
226
            // @link https://stackoverflow.com/questions/41394983/how-to-defer-inline-javascript
227
            if (empty($attributes['cookie-consent']) && strpos($script, 'window.addEventListener') === false) {
228
                $script = "window.addEventListener('DOMContentLoaded', function() { $script });";
229
            }
230
231
            // Remove comments if any
232
            $script = preg_replace('/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/', '', $script);
233
234
            $jsRequirements .= HTML::createTag(
235
                'script',
236
                $attributes,
237
                "//<![CDATA[\n{$script}\n//]]>"
238
            );
239
            $jsRequirements .= "\n";
240
        }
241
242
        // Custom head tags (comes first)
243
        foreach ($this->getCustomHeadTags() as $customHeadTag) {
244
            $requirements .= "{$customHeadTag}\n";
245
        }
246
247
        // CSS file links
248
        foreach ($this->getCSS() as $file => $params) {
249
            $htmlAttributes = [
250
                'rel' => 'stylesheet',
251
                'type' => 'text/css',
252
                'href' => $this->pathForFile($file),
253
            ];
254
            if (!empty($params['media'])) {
255
                $htmlAttributes['media'] = $params['media'];
256
            }
257
            $requirements .= HTML::createTag('link', $htmlAttributes);
258
            $requirements .= "\n";
259
        }
260
261
        // Literal custom CSS content
262
        foreach ($this->getCustomCSS() as $css) {
263
            $requirements .= HTML::createTag('style', ['type' => 'text/css'], "\n{$css}\n");
264
            $requirements .= "\n";
265
        }
266
267
        // Inject CSS  into body
268
        $content = $this->insertTagsIntoHead($requirements, $content);
269
270
        // Inject scripts
271
        if ($this->getForceJSToBottom()) {
272
            $content = $this->insertScriptsAtBottom($jsRequirements, $content);
273
        } elseif ($this->getWriteJavascriptToBody()) {
274
            $content = $this->insertScriptsIntoBody($jsRequirements, $content);
275
        } else {
276
            $content = $this->insertTagsIntoHead($jsRequirements, $content);
277
        }
278
        return $content;
279
    }
280
}
281