ObjectHelper::copyExistingProperties()   C
last analyzed

Complexity

Conditions 12
Paths 45

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 6.9666
c 0
b 0
f 0
cc 12
nc 45
nop 3

How to fix   Complexity   

Long Method

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:

1
<?php
2
3
namespace BWC\Share\Object;
4
5
final class ObjectHelper
6
{
7
    private function __construct() { }
8
9
10
    public static function copyExistingProperties($from, &$to, $stripPrefix = null) {
11
        $fromVars = null;
12
        $toVars = null;
0 ignored issues
show
Unused Code introduced by
$toVars is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
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
}