Complex classes like StrictKeyedIterableTrait 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 StrictKeyedIterableTrait, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 9 | trait StrictKeyedIterableTrait |
||
| 10 | { |
||
| 11 | use CommonMutableContainerTrait; |
||
| 12 | |||
| 13 | public function concatAll() |
||
| 24 | |||
| 25 | public function keys() |
||
| 34 | |||
| 35 | public function map(callable $callback) |
||
| 44 | |||
| 45 | public function mapWithKey($callback) |
||
| 54 | |||
| 55 | public function filter(callable $callback) |
||
| 66 | |||
| 67 | public function filterWithKey($callback) |
||
| 78 | |||
| 79 | public function zip($iterable) |
||
| 93 | |||
| 94 | public function take($size = 1) |
||
| 109 | |||
| 110 | public function takeWhile($fn) |
||
| 122 | |||
| 123 | public function skip($n) |
||
| 136 | |||
| 137 | public function skipWhile($fn) |
||
| 153 | |||
| 154 | public function slice($start, $lenght) |
||
| 173 | |||
| 174 | 1 | public function concat(\Traversable $iterable) |
|
| 189 | |||
| 190 | public function first() |
||
| 198 | |||
| 199 | public function firstKey() |
||
| 207 | |||
| 208 | public function last() |
||
| 216 | |||
| 217 | public function lastKey() |
||
| 225 | |||
| 226 | /** |
||
| 227 | * {@inheritDoc} |
||
| 228 | * @return $this |
||
| 229 | */ |
||
| 230 | public function each(callable $callable) |
||
| 238 | |||
| 239 | /** |
||
| 240 | * {@inheritdoc} |
||
| 241 | */ |
||
| 242 | public function exists(callable $fn) |
||
| 252 | } |
||
| 253 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.