Complex classes like Property 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 Property, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 12 | class Property extends \ReflectionProperty |
||
| 13 | { |
||
| 14 | /** |
||
| 15 | * @var array |
||
| 16 | */ |
||
| 17 | protected static $typeMapping = [ |
||
| 18 | 'int' => 'integer', |
||
| 19 | 'bool' => 'boolean', |
||
| 20 | ]; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var bool |
||
| 24 | */ |
||
| 25 | protected $hasTypeDeclaration = false; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var bool |
||
| 29 | */ |
||
| 30 | protected $isNullable = false; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @var array |
||
| 34 | */ |
||
| 35 | protected $types = []; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * Property constructor. |
||
| 39 | * |
||
| 40 | * @param null|\ReflectionProperty $reflectionProperty |
||
| 41 | * @param object $fakeObject |
||
| 42 | * |
||
| 43 | * @throws \ReflectionException |
||
| 44 | */ |
||
| 45 | 2 | public function __construct($reflectionProperty, $fakeObject = null) |
|
| 49 | |||
| 50 | /** |
||
| 51 | * @param string $type |
||
| 52 | * @param mixed $value |
||
| 53 | * |
||
| 54 | * @return bool |
||
| 55 | */ |
||
| 56 | 6 | protected function assertTypeEquals(string $type, $value): bool |
|
| 70 | |||
| 71 | 6 | public function checkType($value) |
|
| 77 | |||
| 78 | 2 | public static function fromPhpDocumentorProperty(\phpDocumentor\Reflection\DocBlock\Tags\Property $phpDocumentorReflectionProperty): self |
|
| 107 | |||
| 108 | 2 | public function getTypes(): array |
|
| 112 | |||
| 113 | protected function isValidGenericCollection(string $type, $collection): bool |
||
| 129 | |||
| 130 | /** |
||
| 131 | * @param mixed $value |
||
| 132 | * |
||
| 133 | * @return bool |
||
| 134 | */ |
||
| 135 | 6 | protected function isValidType($value): bool |
|
| 155 | |||
| 156 | /** |
||
| 157 | * @param Type $type |
||
| 158 | * |
||
| 159 | * @return string[]|string |
||
| 160 | */ |
||
| 161 | 2 | protected static function parseDocTypeObject(Type $type) |
|
| 219 | |||
| 220 | /** |
||
| 221 | * @param mixed $value |
||
| 222 | */ |
||
| 223 | 2 | protected function throwInvalidType($value) |
|
| 239 | } |
||
| 240 |
If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe: