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