Total Complexity | 49 |
Total Lines | 175 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like ClassWorker often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ClassWorker, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
5 | class ClassWorker |
||
6 | { |
||
7 | public static function applyClass (string $code, string $class, string $apply): string |
||
8 | { |
||
9 | $code = self::stripComments ($code); |
||
10 | |||
11 | $split1 = $split2 = false; |
||
12 | |||
13 | $len = strlen ($code); |
||
14 | $classLen = strlen ($class); |
||
15 | |||
16 | $class_predefined = false; |
||
17 | $class_close = null; |
||
18 | |||
19 | for ($i = 0; $i < $len; ++$i) |
||
20 | { |
||
21 | if ($code[$i] == '\'' && !$split2) |
||
22 | $split1 = !$split1; |
||
|
|||
23 | |||
24 | elseif ($code[$i] == '"' && !$split1) |
||
25 | $split2 = !$split2; |
||
26 | |||
27 | elseif (!$split1 && !$split2) |
||
28 | { |
||
29 | if ($code[$i] == 'c' && substr ($code, $i, 5) == 'class') |
||
30 | { |
||
31 | for ($j = $i + 5; $j < $len; ++$j) |
||
32 | if (in_array ($code[$j], ["\n", "\r", "\t", ' '])) |
||
33 | continue; |
||
34 | |||
35 | else |
||
36 | { |
||
37 | if (substr ($code, $j, $classLen) == $class) |
||
38 | $class_predefined = true; |
||
39 | |||
40 | $i = $j; |
||
41 | |||
42 | break; |
||
43 | } |
||
44 | } |
||
45 | |||
46 | elseif ($class_predefined == true) |
||
47 | { |
||
48 | if ($code[$i] == '{') |
||
49 | { |
||
50 | if ($class_close === null) |
||
51 | $class_close = 1; |
||
52 | |||
53 | else ++$class_close; |
||
54 | } |
||
55 | |||
56 | elseif ($code[$i] == '}') |
||
57 | --$class_close; |
||
58 | |||
59 | if ($class_close === 0) |
||
60 | return substr ($code, 0, $i) . $apply . substr ($code, $i); |
||
61 | } |
||
62 | } |
||
63 | } |
||
64 | |||
65 | return $code; |
||
66 | } |
||
67 | |||
68 | public static function getAvailableClassMethods (string $code, string $class): array |
||
151 | } |
||
152 | |||
153 | public static function stripComments (string $code): string |
||
182 |