Requirements_Backend_For_Webpack::themedRequest()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 0
1
<?php
2
3
/**
4
 * Requirements_Backend_For_Webpack::set_files_to_ignore(
5
 *  'mysite/javascript/myfile.js';
6
 * );
7
 *
8
 *
9
 */
10
class Requirements_Backend_For_Webpack extends Requirements_Backend implements flushable
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
11
{
12
13
    /**
14
     * @var string
15
     */
16
    private static $webpack_variables_file_location = 'themes/webpack-variables.js';
17
18
    /**
19
     * we need this method because Requirements_Backend does not extend Object!
20
     * @param string
21
     */
22
    public static function set_webpack_variables_file_location($str)
0 ignored issues
show
Unused Code introduced by
The parameter $str is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
23
    {
24
        self::$webpack_variables_file_location = $tr;
0 ignored issues
show
Bug introduced by
The variable $tr does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
25
    }
26
27
    /**
28
     * IMPORTANT ... you will use this one more than others ...
29
     * e.g. /mysite/javascript/test.js
30
     * @var array
31
     */
32
    private static $files_to_ignore = [];
33
34
    /**
35
     * we need this method because Requirements_Backend does not extend Object!
36
     * @var array $array
37
     */
38
    public static function set_files_to_ignore($array)
39
    {
40
        self::$files_to_ignore = $array;
41
    }
42
43
    /**
44
     * @return array
45
     */
46
    public static function get_files_to_ignore()
47
    {
48
        return self::$files_to_ignore = $array;
0 ignored issues
show
Bug introduced by
The variable $array does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
49
    }
50
51
    /**
52
     * @var string
53
     */
54
    private static $working_theme_folder_extension = "mysite";
55
56
    /**
57
     * we need this method because Requirements_Backend does not extend Object!
58
     * @var string $string
59
     */
60
    public static function set_working_theme_folder_extension($string)
61
    {
62
        self::$working_theme_folder_extension = $string;
63
    }
64
65
66
    /**
67
     * we need this method because Requirements_Backend does not extend Object!
68
     * @return string
69
     */
70
    public static function get_working_theme_folder_extension()
71
    {
72
        return self::$working_theme_folder_extension = $string;
0 ignored issues
show
Bug introduced by
The variable $string does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
73
    }
74
75
    /**
76
     * @var string
77
     */
78
    private static $copy_css_to_folder = "src/raw_requirements/css";
79
80
    /**
81
     * we need this method because Requirements_Backend does not extend Object!
82
     * @var string $string
83
     */
84
    public static function set_copy_css_to_folder($string)
85
    {
86
        self::$copy_css_to_folder = $string;
87
    }
88
89
    /**
90
     * @var string
91
     */
92
    private static $copy_js_to_folder = "src/raw_requirements/js";
93
94
    /**
95
     * we need this method because Requirements_Backend does not extend Object!
96
     * @param string $string
97
     */
98
    public static function set_copy_js_to_folder($string)
99
    {
100
        self::$copy_js_to_folder = $string;
101
    }
102
103
    /**
104
     * @var array
105
     */
106
    private static $urls_to_exclude = array();
107
108
    /**
109
     * we need this method because Requirements_Backend does not extend Object!
110
     * @param array $array
0 ignored issues
show
Bug introduced by
There is no parameter named $array. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
111
     */
112
    public static function set_urls_to_exclude($a)
113
    {
114
        self::$urls_to_exclude = $a;
115
    }
116
117
    /**
118
     *
119
     * @return array
120
     */
121
    public static function get_urls_to_exclude()
122
    {
123
        return self::$urls_to_exclude;
124
    }
125
126
    /**
127
     * @var bool
128
     */
129
    private static $force_update = true;
130
131
    /**
132
     *
133
     * @param bool
134
     */
135
    public static function set_force_update($bool)
136
    {
137
        self::$force_update = $bool;
138
    }
139
140
141
    /**
142
     *
143
     * @return bool
144
     */
145
    public static function get_force_update($bool)
0 ignored issues
show
Unused Code introduced by
The parameter $bool is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
146
    {
147
        return self::$force_update;
148
    }
149
150
    /**
151
     * Whether to add caching query params to the requests for file-based requirements.
152
     * Eg: themes/myTheme/js/main.js?m=123456789. The parameter is a timestamp generated by
153
     * filemtime. This has the benefit of allowing the browser to cache the URL infinitely,
154
     * while automatically busting this cache every time the file is changed.
155
     *
156
     * @var bool
157
     */
158
    protected $suffix_requirements = false;
159
160
    /**
161
     * Whether to combine CSS and JavaScript files
162
     *
163
     * @var bool
164
     */
165
    protected $combined_files_enabled = false;
166
167
168
    /**
169
     * Force the JavaScript to the bottom of the page, even if there's a script tag in the body already
170
     *
171
     * @var boolean
172
     */
173
    protected $force_js_to_bottom = true;
174
175
176
    /**
177
     * @return string
178
     */
179
    protected static function webpack_current_theme_as_set_in_db()
180
    {
181
        $v = null;
182
        if (Security::database_is_ready()) {
183
            try {
184
                $v = SiteConfig::current_site_config()->Theme;
185
            } catch (Exception $e) {
186
                //dont worry!
187
            }
188
        }
189
        if (! $v) {
190
            $v = Config::inst()->get('SSViewer', 'current_theme');
191
        }
192
193
        if (! $v) {
194
            user_error('We recommend you set a theme as soon as possible.', E_USER_NOTICE);
195
        }
196
197
        return $v;
198
    }
199
200
201
    /**
202
     * @return string
203
     */
204
    protected static function webpack_theme_folder_for_customisation()
205
    {
206
        return '/themes/'.self::webpack_current_theme_as_set_in_db().'_'.self::$working_theme_folder_extension.'/';
207
    }
208
209
210
    /**
211
     * Update the given HTML content with the appropriate include tags for the registered
212
     * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
213
     * including a head and body tag.
214
     *
215
     * @param string $templateFile No longer used, only retained for compatibility
216
     * @param string $content      HTML content that has already been parsed from the $templateFile
217
     *                             through {@link SSViewer}
218
     * @return string HTML content augmented with the requirements tags
219
     */
220
    public function includeInHTML($templateFile, $content)
221
    {
222
        if ($this->themedRequest()) {
223
224
            //=====================================================================
225
            // start copy-ish from parent class
226
227
            $hasHead = (strpos($content, '</head>') !== false || strpos($content, '</head ') !== false) ? true : false;
228
            $hasRequirements = ($this->css || $this->javascript || $this->customCSS || $this->customScript || $this->customHeadTags) ? true: false;
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->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...
229
            if ($hasHead && $hasRequirements) {
230
                $requirements = '';
231
                $jsRequirements = '';
232
                $requirementsCSSFiles = array();
233
                $requirementsJSFiles = array();
234
235
                // Combine files - updates $this->javascript and $this->css
236
                $this->process_combined_files();
237
                $isDev = Director::isDev();
238
                foreach (array_diff_key($this->javascript, $this->blocked) as $file => $dummy) {
239
                    $ignore = in_array($file, self::$files_to_ignore) ? true : false;
240
                    if ($isDev || $ignore) {
241
                        $path = Convert::raw2xml($this->path_for_file($file));
0 ignored issues
show
Bug introduced by
It seems like $this->path_for_file($file) targeting Requirements_Backend::path_for_file() can also be of type boolean; however, Convert::raw2xml() does only seem to accept array|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
242
                        if ($path) {
243
                            if ($isDev) {
244
                                $requirementsJSFiles[$path] = $path;
245
                            }
246
                            if (in_array($file, self::$files_to_ignore)) {
247
                                $jsRequirements .= "<script type=\"text/javascript\" src=\"$path\"></script>\n";
248
                            }
249
                        }
250
                    }
251
                }
252
253
                // Add all inline JavaScript *after* including external files they might rely on
254
                if ($this->customScript) {
0 ignored issues
show
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...
255
                    foreach (array_diff_key($this->customScript, $this->blocked) as $script) {
256
                        $jsRequirements .= "<script type=\"text/javascript\">\n//<![CDATA[\n";
257
                        $jsRequirements .= "$script\n";
258
                        $jsRequirements .= "\n//]]>\n</script>\n";
259
                    }
260
                }
261
262
                foreach (array_diff_key($this->css, $this->blocked) as $file => $params) {
263
                    $ignore = in_array($file, self::$files_to_ignore) ? true : false;
264
                    if ($isDev || $ignore) {
265
                        $path = Convert::raw2xml($this->path_for_file($file));
0 ignored issues
show
Bug introduced by
It seems like $this->path_for_file($file) targeting Requirements_Backend::path_for_file() can also be of type boolean; however, Convert::raw2xml() does only seem to accept array|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
266
                        if ($path) {
267
                            $media = (isset($params['media']) && !empty($params['media'])) ? $params['media'] : "";
268
                            if ($isDev) {
269
                                $requirementsCSSFiles[$path."_".$media] = $path;
270
                            }
271
                            if ($ignore) {
272
                                if ($media !== '') {
273
                                    $media = " media=\"{$media}\"";
274
                                }
275
                                $requirements .= "<link rel=\"stylesheet\" type=\"text/css\"{$media} href=\"$path\" />\n";
276
                            }
277
                        }
278
                    }
279
                }
280
281
                foreach (array_diff_key($this->customCSS, $this->blocked) as $css) {
282
                    $requirements .= "<style type=\"text/css\">\n$css\n</style>\n";
283
                }
284
285
                foreach (array_diff_key($this->customHeadTags, $this->blocked) as $customHeadTag) {
286
                    $requirements .= "$customHeadTag\n";
287
                }
288
289
                // Remove all newlines from code to preserve layout
290
                $jsRequirements = preg_replace('/>\n*/', '>', $jsRequirements);
291
292
                // Forcefully put the scripts at the bottom of the body instead of before the first
293
                // script tag.
294
                $content = preg_replace("/(<\/body[^>]*>)/i", $jsRequirements . "\\1", $content);
295
296
                // Put CSS at the bottom of the head
297
                $content = preg_replace("/(<\/head>)/i", $requirements . "\\1", $content);
298
299
                //end copy-ish from parent class
300
                //=====================================================================
301
302
                //copy files ...
303
                if ($this->canSaveRequirements()) {
304
                    $themeFolderForSavingFiles = self::webpack_theme_folder_for_customisation();
305
                    //css
306
                    $cssFolder = $themeFolderForSavingFiles.self::$copy_css_to_folder;
307
308
                    foreach ($requirementsCSSFiles as $cssFile) {
309
                        $this->moveFileToRequirementsFolder($cssFile, $cssFolder);
310
                    }
311
                    //js
312
                    $jsFolder = $themeFolderForSavingFiles.self::$copy_js_to_folder;
313
                    foreach ($requirementsJSFiles as $jsFile) {
314
                        $this->moveFileToRequirementsFolder($jsFile, $jsFolder);
315
                    }
316
                }
317
            }
318
            return $content;
319
        } else {
320
            return parent::includeInHTML($templateFile, $content);
321
        }
322
    }
323
324
    /**
325
     * Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the given
326
     * HTTP Response
327
     *
328
     * @param SS_HTTPResponse $response
329
     */
330
    public function include_in_response(SS_HTTPResponse $response)
331
    {
332
        if ($this->themedRequest()) {
333
            //do nothing
334
        } else {
335
            return parent::include_in_response($response);
336
        }
337
        //$this->process_combined_files();
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
338
        //do nothing ...
339
    }
340
341
    /**
342
     *
343
     *
344
     *
345
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
346
     */
347
    protected function canSaveRequirements()
348
    {
349
        if (self::webpack_current_theme_as_set_in_db()) {
350
            if (Director::isDev()) {
351
                if ($this->themedRequest()) {
352
                    $socket = @fsockopen('localhost', 3000, $errno, $errstr, 1);
353
                    if ($socket) {
354
                        return true;
355
                    }
356
                }
357
            }
358
        }
359
    }
360
361
    /**
362
     *
363
     *
364
     * @return bool
365
     */
366
    protected function themedRequest()
367
    {
368
        return Config::inst()->get('SSViewer', 'theme') && Config::inst()->get('SSViewer', 'theme_enabled') ? true : false;
369
    }
370
371
    /**
372
     *
373
     * @param  string $fileLocation
374
     * @param  string $folderLocation
375
     *
376
     */
377
    protected function moveFileToRequirementsFolder($fileLocation, $folderLocation)
0 ignored issues
show
Coding Style introduced by
moveFileToRequirementsFolder uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
378
    {
379
        $base = Director::baseFolder();
380
        $folderLocationWithBase = $base . $folderLocation;
381
        Filesystem::makeFolder($folderLocationWithBase);
382
        if (!file_exists($folderLocationWithBase)) {
383
            user_error('Please update Requirements_Backend_For_Webpack for the right folder or create '.$folderLocationWithBase);
384
        }
385
        if (strpos($fileLocation, "//") !== false) {
386
            $logFile = $folderLocationWithBase."/TO.INCLUDE.FROM.PAGE.SS.FILE.log";
387
            $line = $_SERVER['REQUEST_URI']." | ".$fileLocation;
0 ignored issues
show
Unused Code introduced by
$line is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
388
            $this->addLinesToFile($logFile, $fileLocation);
389
        } else {
390
            $from = $fileLocation;
391
            $to = basename($fileLocation);
0 ignored issues
show
Unused Code introduced by
$to is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
392
            $line = '@import \'site'.$from.'\'';
393
            $logFile = $folderLocationWithBase."/TO.INCLUDE.USING.WEBPACK.METHODS.log";
394
            $this->addLinesToFile($logFile, $line);
395
            if (in_array($fileLocation, self::$files_to_ignore)) {
396
                //to be completed ...
397
            } else {
398
                // if (! file_exists($to) || self::$force_update) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
399
                //     copy($from, $to);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
400
                // }
401
            }
402
        }
403
    }
404
405
    protected function copyIfYouCan($from, $to, $count = 0)
406
    {
407
        try {
408
            copy($from, $to);
409
        } catch (Exception $e) {
410
            $count++;
411
            $this->makeFolderWritable();
0 ignored issues
show
Bug introduced by
The call to makeFolderWritable() misses a required argument $fileLocation.

This check looks for function calls that miss required arguments.

Loading history...
412
            if ($count < 3) {
413
                $this->copyIfYouCan($from, $to, $count);
414
            }
415
        }
416
    }
417
418
    protected function addLinesToFile($fileLocation, $line, $count = 0)
419
    {
420
        $line .= "\n";
421
        try {
422
            $lines = [];
423
            if (file_exists($fileLocation)) {
424
                $lines = file($fileLocation);
425
            }
426
            if (! in_array($line, $lines)) {
427
                //last catch!
428
                if (is_writable($fileLocation)) {
429
                    $handle = fopen($fileLocation, 'a');
430
                    fwrite($handle, $line);
431
                }
432
            }
433
        } catch (Exception $e) {
434
            $this->makeFolderWritable();
0 ignored issues
show
Bug introduced by
The call to makeFolderWritable() misses a required argument $fileLocation.

This check looks for function calls that miss required arguments.

Loading history...
435
            $count++;
436
            if ($count < 3) {
437
                $this->addLinesToFile($fileLocation, $lines, $count);
438
            }
439
        }
440
    }
441
442
    protected function makeFolderWritable($fileLocation)
443
    {
444
        if (file_exists($fileLocation)) {
445
            $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname($fileLocation)));
446
            foreach ($iterator as $item) {
447
                chmod($item, '0664');
448
            }
449
        }
450
    }
451
452
453
    public static function flush()
0 ignored issues
show
Coding Style introduced by
flush uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
454
    {
455
        if (Director::isDev()) {
456
            $theme = self::webpack_current_theme_as_set_in_db();
457
            $distributionFolderExtension = Config::inst()->get('WebpackPageControllerExtension', 'webpack_distribution_folder_extension');
458
            if ($theme) {
459
                //make raw requirements writeable
460
                $base = Director::baseFolder();
461
                $themeFolderForCustomisation = self::webpack_theme_folder_for_customisation();
462
                $rawFolders = [
463
                    $base.$themeFolderForCustomisation.'src/sass',
464
                    $base.$themeFolderForCustomisation.''.self::$copy_css_to_folder,
465
                    $base.$themeFolderForCustomisation.''.self::$copy_js_to_folder,
466
                    $base.'/'.THEMES_DIR . "/" . $theme.'_'.$distributionFolderExtension
467
                ];
468
                foreach ($rawFolders as $folder) {
469
                    Filesystem::makeFolder($folder);
470
                }
471
                $files = [
472
                    $base.$themeFolderForCustomisation.'src/main.js',
473
                    $base.$themeFolderForCustomisation.'src/sass/style.sass'
474
                ];
475
                foreach ($files as $file) {
476
                    if (!file_exists($file)) {
477
                        file_put_contents($file, '//add your customisations in this file');
478
                    }
479
                }
480
481
                $varArray = [
482
                    'themeName' => self::webpack_current_theme_as_set_in_db(),
483
                    'devWebAddress' => isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : Director::protocolAndHost(),
484
                    'distributionFolder' => self::webpack_current_theme_as_set_in_db().'_'.Config::inst()->get('WebpackPageControllerExtension', 'webpack_distribution_folder_extension')
485
                ];
486
                $str = 'module.exports = '.json_encode($varArray).'';
487
                @file_put_contents($base.'/'.self::$webpack_variables_file_location, $str);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
488
            }
489
        }
490
    }
491
}
492