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 | 56 | public function isTuple($array) |
|
28 | |||
29 | 56 | public function toObject($data) |
|
30 | { |
||
31 | 56 | if (is_array($data)) { |
|
32 | 56 | if ($this->isTuple($data)) { |
|
33 | 56 | return $this->convertArrayToObject($data); |
|
34 | } |
||
35 | } |
||
36 | |||
37 | 56 | if (is_object($data)) { |
|
38 | 5 | if ($data instanceof Entity) { |
|
39 | // keep instance |
||
40 | 3 | return $data; |
|
41 | } |
||
42 | |||
43 | 2 | $tmp = $data; |
|
44 | 2 | $data = []; |
|
45 | 2 | foreach ($tmp as $k => $v) { |
|
46 | 2 | $data[$k] = $v; |
|
47 | } |
||
48 | } |
||
49 | |||
50 | 56 | $data = (object) $data; |
|
51 | |||
52 | 56 | foreach ($data as $k => $v) { |
|
53 | 56 | if (is_array($v) && $this->isTuple($v)) { |
|
54 | 56 | $data->$k = $this->convertArrayToObject($v); |
|
55 | 56 | } elseif (is_array($v) || is_object($v)) { |
|
56 | 10 | $data->$k = $this->toObject($v); |
|
57 | } |
||
58 | } |
||
59 | |||
60 | 56 | return $data; |
|
61 | } |
||
62 | |||
63 | 56 | public function convertArrayToObject($data) |
|
77 | |||
78 | 11 | public function toArray($data) : array |
|
96 | |||
97 | private $underscores = []; |
||
98 | |||
99 | 1 | public function toUnderscore(string $input) : string |
|
111 | |||
112 | private $camelcased = []; |
||
113 | |||
114 | 1 | public function toCamelCase(string $string, bool $capitalize = false) : string |
|
133 | |||
134 | |||
135 | private $dates = []; |
||
136 | |||
137 | 1 | public function getDate($string) |
|
160 | |||
161 | 1 | public function getTimestamp($string) |
|
165 | |||
166 | 1 | public function getPluralForm($n, $forms) |
|
170 | } |
||
171 |
It seems like the method you are trying to call exists only in some of the possible types.
Let’s take a look at an example:
Available Fixes
Add an additional type-check:
Only allow a single type to be passed if the variable comes from a parameter: