Complex classes like Converter 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 Converter, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
10 | class Converter |
||
11 | { |
||
12 | 45 | public function isTuple($array) |
|
13 | { |
||
14 | 45 | if (is_object($array)) { |
|
15 | $array = get_object_vars($array); |
||
16 | } |
||
17 | 45 | if (!is_array($array)) { |
|
18 | 10 | return false; |
|
19 | } |
||
20 | 45 | return !count($array) || array_keys($array) === range(0, count($array) -1); |
|
21 | } |
||
22 | |||
23 | 45 | public function toObject($data) |
|
24 | { |
||
25 | 45 | if (is_array($data)) { |
|
26 | 45 | if ($this->isTuple($data)) { |
|
27 | 45 | return $this->convertArrayToObject($data); |
|
28 | } |
||
29 | } |
||
30 | |||
31 | 45 | if (is_object($data)) { |
|
32 | 5 | if ($data instanceof Entity) { |
|
33 | // keep instance |
||
34 | return $data; |
||
35 | } |
||
36 | |||
37 | 5 | $tmp = $data; |
|
38 | 5 | $data = []; |
|
39 | 5 | foreach ($tmp as $k => $v) { |
|
40 | 1 | $data[$k] = $v; |
|
41 | } |
||
42 | } |
||
43 | |||
44 | 45 | $data = (object) $data; |
|
45 | |||
46 | 45 | foreach ($data as $k => $v) { |
|
47 | 45 | if (is_array($v) && $this->isTuple($v)) { |
|
48 | 45 | $data->$k = $this->convertArrayToObject($v); |
|
49 | 45 | } elseif(is_array($v) || is_object($v)) { |
|
50 | 45 | $data->$k = $this->toObject($v); |
|
51 | } |
||
52 | } |
||
53 | |||
54 | 45 | return $data; |
|
55 | } |
||
56 | |||
57 | 45 | public function convertArrayToObject($data) |
|
71 | |||
72 | 11 | public function toArray($data) : array |
|
90 | |||
91 | private $underscores = []; |
||
92 | |||
93 | 1 | public function toUnderscore(string $input) : string |
|
105 | |||
106 | private $camelcased = []; |
||
107 | |||
108 | 1 | public function toCamelCase(string $string, bool $capitalize = false) : string |
|
127 | |||
128 | |||
129 | private $dates = []; |
||
130 | |||
131 | 1 | public function getDate($string) |
|
154 | |||
155 | 1 | public function getTimestamp($string) |
|
159 | |||
160 | } |
||
161 |
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.