Completed
Push — master ( 4e9ed0...aeb84d )
by Nicolaas
01:12
created

Requirements_Backend_For_Webpack::addLinesToFile()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 3
nop 2
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
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
    /**
15
     * e.g. /mysite/javascript/test.js
16
     * @ var array
17
     */
18
    private static $files_to_ignore = array();
19
20
    /**
21
     * we need this method because Requirements_Backend does not extend Object!
22
     * @param array $array
23
     */
24
    public static function set_files_to_ignore($array)
25
    {
26
        self::$files_to_ignore = $array;
27
    }
28
29
    /**
30
     * @ var string
31
     */
32
    private static $working_theme_folder_extension = "_mysite";
33
34
    /**
35
     * @ var string
36
     */
37
    private static $copy_css_to_folder = "src/raw_requirements/css";
38
39
    /**
40
     * we need this method because Requirements_Backend does not extend Object!
41
     * @param string $string
42
     */
43
    public static function set_copy_css_to_folder($string)
44
    {
45
        self::$copy_css_to_folder = $string;
46
    }
47
48
    /**
49
     * @ var string
50
     */
51
    private static $copy_js_to_folder = "src/raw_requirements/js";
52
53
    /**
54
     * we need this method because Requirements_Backend does not extend Object!
55
     * @param string $string
56
     */
57
    public static function set_copy_js_to_folder($string)
58
    {
59
        self::$copy_js_to_folder = $string;
60
    }
61
62
    /**
63
     * @ var string
64
     */
65
    private static $urls_to_exclude = array();
66
67
    /**
68
     * we need this method because Requirements_Backend does not extend Object!
69
     * @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...
70
     */
71
    public static function set_urls_to_exclude($a)
72
    {
73
        self::$urls_to_exclude = $a;
74
    }
75
    public static function get_urls_to_exclude()
76
    {
77
        return self::$urls_to_exclude;
78
    }
79
80
    /**
81
     * @ var bool
82
     */
83
    private static $force_update = true;
84
    public static function set_force_update($bool)
85
    {
86
        self::$force_update = $bool;
87
    }
88
    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...
89
    {
90
        return self::$force_update;
91
    }
92
93
    /**
94
     * Whether to add caching query params to the requests for file-based requirements.
95
     * Eg: themes/myTheme/js/main.js?m=123456789. The parameter is a timestamp generated by
96
     * filemtime. This has the benefit of allowing the browser to cache the URL infinitely,
97
     * while automatically busting this cache every time the file is changed.
98
     *
99
     * @var bool
100
     */
101
    protected $suffix_requirements = false;
102
103
    /**
104
     * Whether to combine CSS and JavaScript files
105
     *
106
     * @var bool
107
     */
108
    protected $combined_files_enabled = false;
109
110
111
    /**
112
     * Force the JavaScript to the bottom of the page, even if there's a script tag in the body already
113
     *
114
     * @var boolean
115
     */
116
    protected $force_js_to_bottom = true;
117
118
    /**
119
     * Update the given HTML content with the appropriate include tags for the registered
120
     * requirements. Needs to receive a valid HTML/XHTML template in the $content parameter,
121
     * including a head and body tag.
122
     *
123
     * @param string $templateFile No longer used, only retained for compatibility
124
     * @param string $content      HTML content that has already been parsed from the $templateFile
125
     *                             through {@link SSViewer}
126
     * @return string HTML content augmented with the requirements tags
127
     */
128
    public function includeInHTML($templateFile, $content)
129
    {
130
        if ($this->themedRequest()) {
131
132
            //=====================================================================
133
            // start copy-ish from parent class
134
135
            $hasHead = (strpos($content, '</head>') !== false || strpos($content, '</head ') !== false) ? true : false;
136
            $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...
137
            if ($hasHead && $hasRequirements) {
138
                $requirements = '';
139
                $jsRequirements = '';
140
                $requirementsCSSFiles = array();
141
                $requirementsJSFiles = array();
142
143
                // Combine files - updates $this->javascript and $this->css
144
                $this->process_combined_files();
145
                $isDev = Director::isDev();
146
                foreach (array_diff_key($this->javascript, $this->blocked) as $file => $dummy) {
147
                    $ignore = in_array($file, self::$files_to_ignore) ? true : false;
148
                    if($isDev || $ignore) {
149
                        $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...
150
                        if ($path) {
151
                            if ($isDev) {
152
                                $requirementsJSFiles[$path] = $path;
153
                            }
154
                            if(in_array($file, self::$files_to_ignore)) {
155
                                $jsRequirements .= "<script type=\"text/javascript\" src=\"$path\"></script>\n";
156
                            }
157
                        }
158
                    }
159
                }
160
161
                // Add all inline JavaScript *after* including external files they might rely on
162
                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...
163
                    foreach (array_diff_key($this->customScript, $this->blocked) as $script) {
164
                        $jsRequirements .= "<script type=\"text/javascript\">\n//<![CDATA[\n";
165
                        $jsRequirements .= "$script\n";
166
                        $jsRequirements .= "\n//]]>\n</script>\n";
167
                    }
168
                }
169
170
                foreach (array_diff_key($this->css, $this->blocked) as $file => $params) {
171
                    $ignore = in_array($file, self::$files_to_ignore) ? true : false;
172
                    if($isDev || $ignore) {
173
                        $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...
174
                        if ($path) {
175
                            $media = (isset($params['media']) && !empty($params['media'])) ? $params['media'] : "";
176
                            if ($isDev) {
177
                                $requirementsCSSFiles[$path."_".$media] = $path;
178
                            }
179
                            if($ignore) {
180
                                if($media !== '') {
181
                                    $media = " media=\"{$media}\"";
182
                                }
183
                                $requirements .= "<link rel=\"stylesheet\" type=\"text/css\"{$media} href=\"$path\" />\n";
184
                            }
185
                        }
186
                    }
187
                }
188
189
                foreach (array_diff_key($this->customCSS, $this->blocked) as $css) {
190
                    $requirements .= "<style type=\"text/css\">\n$css\n</style>\n";
191
                }
192
193
                foreach (array_diff_key($this->customHeadTags, $this->blocked) as $customHeadTag) {
194
                    $requirements .= "$customHeadTag\n";
195
                }
196
197
                // Remove all newlines from code to preserve layout
198
                $jsRequirements = preg_replace('/>\n*/', '>', $jsRequirements);
199
200
                // Forcefully put the scripts at the bottom of the body instead of before the first
201
                // script tag.
202
                $content = preg_replace("/(<\/body[^>]*>)/i", $jsRequirements . "\\1", $content);
203
204
                // Put CSS at the bottom of the head
205
                $content = preg_replace("/(<\/head>)/i", $requirements . "\\1", $content);
206
207
                //end copy-ish from parent class
208
                //=====================================================================
209
210
                //copy files ...
211
                if ($this->canSaveRequirements()) {
212
213
                    //css
214
                    $cssFolder = '/themes/'.SSViewer::current_theme().self::$working_theme_folder_extension.'/'.self::$copy_css_to_folder;
0 ignored issues
show
Deprecated Code introduced by
The method SSViewer::current_theme() has been deprecated with message: 4.0 Use the "SSViewer.theme" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
215
216
                    foreach ($requirementsCSSFiles as $cssFile) {
217
                        $this->moveFileToRequirementsFolder($cssFile, $cssFolder);
218
                    }
219
                    //js
220
                    $jsFolder = '/themes/'.SSViewer::current_theme().self::$working_theme_folder_extension.'/'.self::$copy_js_to_folder;
0 ignored issues
show
Deprecated Code introduced by
The method SSViewer::current_theme() has been deprecated with message: 4.0 Use the "SSViewer.theme" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
221
                    foreach ($requirementsJSFiles as $jsFile) {
222
                        $this->moveFileToRequirementsFolder($jsFile, $jsFolder);
223
                    }
224
                }
225
            }
226
            return $content;
227
        } else {
228
            return parent::includeInHTML($templateFile, $content);
229
        }
230
    }
231
232
    /**
233
     * Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the given
234
     * HTTP Response
235
     *
236
     * @param SS_HTTPResponse $response
237
     */
238
    public function include_in_response(SS_HTTPResponse $response)
239
    {
240
        if ($this->themedRequest()) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
241
            //do nothing
242
        } else {
243
            return parent::include_in_response($response);
244
        }
245
        //$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...
246
        //do nothing ...
247
    }
248
249
    /**
250
     *
251
     *
252
     *
253
     * @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...
254
     */
255
    protected function canSaveRequirements()
256
    {
257
        if (Director::isDev()) {
258
            if ($this->themedRequest()) {
259
                $socket = @fsockopen('localhost', 3000, $errno, $errstr, 1);
260
                if ($socket) {
261
                    return true;
262
                }
263
            }
264
        }
265
    }
266
267
    /**
268
     *
269
     *
270
     * @return bool
271
     */
272
    protected function themedRequest()
273
    {
274
        return Config::inst()->get('SSViewer', 'theme') && Config::inst()->get('SSViewer', 'theme_enabled') ? true : false;
275
    }
276
277
    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...
278
    {
279
        $base = Director::baseFolder();
280
        $folderLocationWithBase = $base . $folderLocation;
281
        Filesystem::makeFolder($folderLocationWithBase);
282
        if (!file_exists($folderLocationWithBase)) {
283
            user_error('Please update Requirements_Backend_For_Webpack for the right folder or create '.$folderLocationWithBase);
284
        }
285
        if (strpos($fileLocation, "//") !== false) {
286
            $logFile = $folderLocationWithBase."/EXTERNALS.log";
287
            $lines = array();
288
            $line = $_SERVER['REQUEST_URI']." | ".$fileLocation."\n";
289
            if (file_exists($logFile)) {
290
                $lines = file($logFile);
291
            }
292
            if (! in_array($line, $lines)) {
293
                $this->addLinesToFile($logFile, $fileLocation);
294
            }
295
        } else {
296
            $from = $fileLocation;
297
            $to = basename($fileLocation);
298
            $line = '"cp .'.$from.' .'.$folderLocation.$to.'",'."\n";
299
            $from = $base.$from;
300
            $to = $folderLocationWithBase . '/' . $to;
301
            $logFile = $folderLocationWithBase."/TO.INCLUDE.IN.COMPOSER.log";
302
            $lines = array();
303
            if (file_exists($logFile)) {
304
                $lines = file($logFile);
305
            }
306
            if (! in_array($line, $lines)) {
307
                $this->addLinesToFile($logFile, $line);
308
            }
309
            if (in_array($fileLocation, self::$files_to_ignore)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
310
                //to be completed ...
311
            } else {
312
                if (! file_exists($to) || self::$force_update) {
313
                    copy($from, $to);
314
                }
315
            }
316
        }
317
    }
318
319
    protected $addLinesToFileCount = 0;
320
321
    protected function copyIfYouCan($from, $to)
322
    {
323
        try {
324
            copy($from, $to);
325
        }
326
        catch(Exception $e) {
327
            $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...
328
            $this->copyIfYouCan($from, $to);
329
        }
330
    }
331
332
    protected function addLinesToFile($fileLocation, $line)
333
    {
334
        try {
335
            $handle = fopen($fileLocation, 'a');
336
            fwrite($handle, $line);
337
        }
338
        catch(Exception $e) {
339
            $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...
340
            $this->addLinesToFile($fileLocation, $lines);
0 ignored issues
show
Bug introduced by
The variable $lines 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...
341
        }
342
    }
343
344
    protected function makeFolderWritable($fileLocation)
345
    {
346
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname($fileLocation)));
347
        foreach($iterator as $item) {
348
            chmod($item, '0775');
349
            chown($item, 'www-data:www-data');
350
        }
351
        if($this->addLinesToFileCount < 3) {
352
            $this->addLinesToFileCount++;
353
        }
354
355
    }
356
}
357