Completed
Push — master ( 6c3722...239355 )
by Matthew
19:49 queued 17:50
created

Util::copyProperties()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 10
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 3
nop 4
crap 20
1
<?php
2
3
namespace Dtc\QueueBundle\Util;
4
5
class Util
6
{
7
    /**
8
     * Copies the members of obj1 that have public getters to obj2 if there exists a public setter in obj2 of the same suffix, it will also copy public variables.
9
     *
10
     * @param $obj1
11
     * @param $obj2
12
     */
13
    public static function copy($obj1, $obj2)
14
    {
15
        if (!is_object($obj1)) {
16
            throw new \Exception('$obj1 must be an object, not '.gettype($obj1));
17
        }
18
        if (!is_object($obj2)) {
19
            throw new \Exception('$obj2 must be an object, not '.gettype($obj2));
20
        }
21
        $reflection1 = new \ReflectionObject($obj1);
22
        $reflection2 = new \ReflectionObject($obj2);
23
        self::copyMethods($obj1, $obj2, $reflection1, $reflection2);
24
        self::copyProperties($obj1, $obj2, $reflection1, $reflection2);
25
    }
26
27
    private static function copyProperties($obj1, $obj2, \ReflectionObject $reflection1, \ReflectionObject $reflection2)
28
    {
29
        $publicVars = $reflection1->getProperties(\ReflectionProperty::IS_PUBLIC);
30
        foreach ($publicVars as $property) {
31
            $propertyName = $property->getName();
32
            if ($reflection2->hasProperty($propertyName) && $reflection2->getProperty($propertyName)->isPublic()) {
33
                $obj2->$propertyName = $obj1->$propertyName;
34
            }
35
        }
36
    }
37
38
    private static function copyMethods($obj1, $obj2, \ReflectionObject $reflection1, \ReflectionObject $reflection2)
39
    {
40
        $methods = $reflection1->getMethods(\ReflectionMethod::IS_PUBLIC);
41
        foreach ($methods as $method) {
42
            $methodName = $method->name;
43
            if (0 === strpos($methodName, 'get')) {
44
                $getMethod = $methodName;
45
                $setMethod = $methodName;
46
                $setMethod[0] = 's';
47
                self::copyMethod($obj1, $obj2, $getMethod, $setMethod, $reflection2);
48
            }
49
        }
50
    }
51
52
    private static function copyMethod($obj1, $obj2, $getMethod, $setMethod, \ReflectionObject $reflection2)
53
    {
54
        if ($reflection2->hasMethod($setMethod)) {
55
            $value = $obj1->$getMethod();
56
            if (null !== $value) {
57
                $obj2->$setMethod($value);
58
            }
59
        }
60
    }
61
}
62