Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 22 | class TraitMetadata |
||
| 23 | { |
||
| 24 | /** |
||
| 25 | * @var string |
||
| 26 | */ |
||
| 27 | private $name; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * @var TraitMetadata[] |
||
| 31 | */ |
||
| 32 | private $traits; |
||
| 33 | |||
| 34 | /** |
||
| 35 | * @var MethodMetadata[] |
||
| 36 | */ |
||
| 37 | private $methods; |
||
| 38 | |||
| 39 | /** |
||
| 40 | * @var Trait_ |
||
| 41 | */ |
||
| 42 | private $ast; |
||
| 43 | |||
| 44 | public function __construct($name, array $traits = [], array $methods = [], Trait_ $ast = null) |
||
| 56 | |||
| 57 | /** |
||
| 58 | * @return string |
||
| 59 | */ |
||
| 60 | public function getName() |
||
| 64 | |||
| 65 | /** |
||
| 66 | * @return bool |
||
| 67 | */ |
||
| 68 | public function hasTraits() |
||
| 72 | |||
| 73 | /** |
||
| 74 | * @return TraitMetadata[] |
||
| 75 | */ |
||
| 76 | public function getTraits() |
||
| 80 | |||
| 81 | /** |
||
| 82 | * @return MethodMetadata[] |
||
| 83 | */ |
||
| 84 | public function getMethods() |
||
| 88 | |||
| 89 | /** |
||
| 90 | * Check if trait has method, with optional trait traverse. |
||
| 91 | * |
||
| 92 | * @param string $name |
||
| 93 | * @param bool $traverse |
||
| 94 | * |
||
| 95 | * @return bool |
||
| 96 | */ |
||
| 97 | View Code Duplication | public function hasMethod($name, $traverse = true) |
|
| 121 | |||
| 122 | /** |
||
| 123 | * Check if trait has public method, with optional trait traverse. |
||
| 124 | * |
||
| 125 | * @param string $name |
||
| 126 | * @param bool $traverse |
||
| 127 | * |
||
| 128 | * @return bool |
||
| 129 | */ |
||
| 130 | View Code Duplication | public function hasPublicMethod($name, $traverse = true) |
|
| 154 | |||
| 155 | /** |
||
| 156 | * Get public method for trait, with optional trait traverse. |
||
| 157 | * |
||
| 158 | * @param string $name |
||
| 159 | * @param bool $traverse |
||
| 160 | * |
||
| 161 | * @return MethodMetadata |
||
| 162 | * |
||
| 163 | * @throws \RunOpenCode\AbstractBuilder\Exception\RuntimeException |
||
| 164 | */ |
||
| 165 | public function getPublicMethod($name, $traverse = true) |
||
| 194 | |||
| 195 | /** |
||
| 196 | * @return Trait_ |
||
| 197 | */ |
||
| 198 | public function getAst() |
||
| 202 | |||
| 203 | /** |
||
| 204 | * {@inheritdoc} |
||
| 205 | */ |
||
| 206 | public function __toString() |
||
| 210 | } |
||
| 211 |
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: