Completed
Push — master ( 40b87c...f82b1c )
by Matthew
04:37
created

Util::copy()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.072

Importance

Changes 2
Bugs 2 Features 0
Metric Value
dl 0
loc 13
ccs 8
cts 10
cp 0.8
rs 9.4285
c 2
b 2
f 0
cc 3
eloc 9
nc 3
nop 2
crap 3.072
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 7
    public static function copy($obj1, $obj2)
14
    {
15 7
        if (!is_object($obj1)) {
16
            throw new \Exception('$obj1 must be an object, not '.gettype($obj1));
17
        }
18 7
        if (!is_object($obj2)) {
19
            throw new \Exception('$obj2 must be an object, not '.gettype($obj2));
20
        }
21 7
        $reflection1 = new \ReflectionObject($obj1);
22 7
        $reflection2 = new \ReflectionObject($obj2);
23 7
        self::copyMethods($obj1, $obj2, $reflection1, $reflection2);
24 7
        self::copyProperties($obj1, $obj2, $reflection1, $reflection2);
25 7
    }
26
27 7
    private static function copyProperties($obj1, $obj2, \ReflectionObject $reflection1, \ReflectionObject $reflection2)
28
    {
29 7
        $publicVars = $reflection1->getProperties(\ReflectionProperty::IS_PUBLIC);
30 7
        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 7
    }
37
38 7
    private static function copyMethods($obj1, $obj2, \ReflectionObject $reflection1, \ReflectionObject $reflection2)
39
    {
40 7
        $methods = $reflection1->getMethods(\ReflectionMethod::IS_PUBLIC);
41 7
        foreach ($methods as $method) {
42 7
            $methodName = $method->name;
43 7
            if (0 === strpos($methodName, 'get')) {
44 7
                $getMethod = $methodName;
45 7
                $setMethod = $methodName;
46 7
                $setMethod[0] = 's';
47 7
                self::copyMethod($obj1, $obj2, $getMethod, $setMethod, $reflection2);
48
            }
49
        }
50 7
    }
51
52 7
    private static function copyMethod($obj1, $obj2, $getMethod, $setMethod, \ReflectionObject $reflection2)
53
    {
54 7
        if ($reflection2->hasMethod($setMethod)) {
55 7
            $value = $obj1->$getMethod();
56 7
            if (null !== $value) {
57 7
                $obj2->$setMethod($value);
58
            }
59
        }
60 7
    }
61
}
62