| Conditions | 12 |
| Paths | 45 |
| Total Lines | 35 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 10 | public static function copyExistingProperties($from, &$to, $stripPrefix = null) { |
||
| 11 | $fromVars = null; |
||
| 12 | $toVars = null; |
||
|
|
|||
| 13 | if (is_object($from)) { |
||
| 14 | $fromVars = get_object_vars($from); |
||
| 15 | } else if (is_array($from)) { |
||
| 16 | $fromVars = $from; |
||
| 17 | } |
||
| 18 | if ($fromVars === null) throw new \InvalidArgumentException('Source must be an object or array'); |
||
| 19 | if (!is_object($to)) throw new \InvalidArgumentException('Destination must be an object'); |
||
| 20 | $toVars = get_object_vars($to); |
||
| 21 | foreach ($fromVars as $prop=>$value) { |
||
| 22 | if (array_key_exists($prop, $toVars)) { |
||
| 23 | $to->$prop = $value; |
||
| 24 | } else { |
||
| 25 | $methodName = 'set'.ucfirst($prop); |
||
| 26 | if (method_exists($to, $methodName)) { |
||
| 27 | $to->{$methodName}($value); |
||
| 28 | } |
||
| 29 | } |
||
| 30 | if ($stripPrefix && strpos($prop, $stripPrefix) === 0) { |
||
| 31 | $p = substr($prop, strlen($stripPrefix)); |
||
| 32 | if (array_key_exists($p, $toVars)) { |
||
| 33 | $to->$p = $value; |
||
| 34 | unset($toVars[$p]); |
||
| 35 | } else { |
||
| 36 | $methodName = 'set'.ucfirst($prop); |
||
| 37 | if (method_exists($to, $methodName)) { |
||
| 38 | $to->{$methodName}($value); |
||
| 39 | } |
||
| 40 | unset($toVars[$p]); |
||
| 41 | } |
||
| 42 | } |
||
| 43 | } |
||
| 44 | } |
||
| 45 | |||
| 46 | } |
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVarassignment in line 1 and the$higherassignment in line 2 are dead. The first because$myVaris never used and the second because$higheris always overwritten for every possible time line.