Complex classes like PathIterator 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 PathIterator, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
9 | class PathIterator implements Iterator |
||
10 | { |
||
11 | const IS_MATCH = 'IS_MATCH'; |
||
12 | const DESCENDANTS_COULD_MATCH = 'DESCENDANTS_COULD_MATCH'; |
||
13 | const DESCENDANTS_CANT_MATCH = 'DESCENDANTS_CANT_MATCH'; |
||
14 | |||
15 | /* |
||
16 | * The list of return codes for filtering callback function |
||
17 | */ |
||
18 | /* |
||
19 | * Valid elem, no filtering. |
||
20 | */ |
||
21 | const ELEMENT_IS_VALID = 1; // elem |
||
22 | /* |
||
23 | * Invalid elem and its descendants, so have to be filtered out. |
||
24 | */ |
||
25 | const ELEMENT_IS_INVALID = 2; |
||
26 | /* |
||
27 | * The same as `ELEMENT_IS_INVALID`. Additionaly after it sibling elems(and its descendants) have to be filtered out too. |
||
28 | */ |
||
29 | const SIBLINGS_ARE_INVALID = 3; |
||
30 | |||
31 | protected $reader; |
||
32 | protected $searchPath; |
||
33 | protected $searchCrumbs; |
||
34 | protected $crumbs; |
||
35 | protected $currentDomExpansion; |
||
36 | protected $rewindCount; |
||
37 | protected $isValid; |
||
38 | protected $returnType; |
||
39 | |||
40 | /* |
||
41 | * Filtering callback function |
||
42 | */ |
||
43 | protected $callback; |
||
44 | |||
45 | public function __construct(ExceptionThrowingXMLReader $reader, $path, $returnType, $callback = null) |
||
57 | |||
58 | public function current() |
||
62 | |||
63 | public function key() |
||
67 | |||
68 | public function next() |
||
77 | |||
78 | public function rewind() |
||
86 | |||
87 | public function valid() |
||
91 | |||
92 | protected function getXMLObject() |
||
116 | |||
117 | protected function pathIsMatching() |
||
134 | |||
135 | protected function searchForOpenTag(XMLReader $r) |
||
143 | |||
144 | public function tryGotoNextIterationElement() |
||
205 | } |
||
206 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: