Conditions | 4 |
Paths | 2 |
Total Lines | 58 |
Code Lines | 33 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
1 | <?php |
||
30 | private function minifyJavascript(string $buffer): string |
||
31 | { |
||
32 | $tags = ['close' => \strrchr($buffer, '<')]; |
||
33 | $open_length = \strpos($buffer, '>') + 1; |
||
34 | $tags['open'] = \substr($buffer, 0, $open_length); |
||
35 | $buffer = \substr($buffer, $open_length, -\strlen($tags['close'])); |
||
36 | |||
37 | // Strip spaces from the tags |
||
38 | $tags = \preg_replace('/\s{2,}/', ' ', $tags); |
||
39 | |||
40 | // Catch all string literals and comment blocks |
||
41 | if (\preg_match_all( |
||
42 | '#((?:((?<!\\\)\'|")|(/\*)|(//)).*(?(2)(?<!\\\)\2|(?(3)\*/|\n)))#msuUS', |
||
43 | $buffer, |
||
44 | $match, |
||
45 | \PREG_OFFSET_CAPTURE |
||
46 | )) { |
||
47 | $js_literals = $js_code = []; |
||
48 | for ($match = $match[0], $c = \count($match), $i = $pos = $offset = 0; $i < $c; $i++) { |
||
49 | $js_code[$pos++] = \trim(\substr($buffer, $offset, $match[$i][1] - $offset)); |
||
50 | $offset = $match[$i][1] + \strlen($match[$i][0]); |
||
51 | |||
52 | // Save only if we haven't matched a comment block |
||
53 | if ($match[$i][0][0] !== '/') { |
||
54 | $js_literals[$pos++] = \array_shift($match[$i]); |
||
55 | } |
||
56 | } |
||
57 | $js_code[$pos] = \substr($buffer, $offset); |
||
58 | |||
59 | // $match might be quite large, so free it up together with other vars that we no longer need |
||
60 | unset($match, $offset, $pos); |
||
61 | } else { |
||
62 | $js_code = [$buffer]; |
||
63 | $js_literals = []; |
||
64 | } |
||
65 | |||
66 | // Standartize new lines |
||
67 | $js_code = \str_replace(["\r\n", "\r"], "\n", $js_code); |
||
68 | |||
69 | $patterns = [ |
||
70 | // Remove spaces following and preceeding JS-wise non-special & non-word characters |
||
71 | '#\s*([!\#%&()*+,\-./:;<=>?@\[\]^`{|}~])\s*#' => '$1', |
||
72 | // Reduce the remaining multiple whitespace characters to a single space |
||
73 | '#\s{2,}#' => ' ', |
||
74 | ]; |
||
75 | |||
76 | $js_code = \preg_replace( |
||
77 | \array_keys($patterns), |
||
78 | \array_values($patterns), |
||
79 | $js_code |
||
80 | ); |
||
81 | |||
82 | // Glue back JS quoted strings |
||
83 | $js_code += $js_literals; |
||
84 | \ksort($js_code); |
||
85 | $buffer = \implode($js_code); |
||
86 | |||
87 | return $tags['open'] . $buffer . $tags['close']; |
||
88 | } |
||
90 |