Skip to content

Commit 804c17d

Browse files
committed
Merge pull request #2 from DavertMik/master
Fixed cloning non-clonable items
2 parents 1ee5325 + 6247d82 commit 804c17d

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/DeepCopy/DeepCopy.php

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,19 @@ class DeepCopy
2222
*/
2323
private $filters = [];
2424

25+
private $skipUncloneable = false;
26+
27+
/**
28+
* Cloning uncloneable properties won't throw exception.
29+
* @param $skipUncloneable
30+
* @return $this
31+
*/
32+
public function skipUncloneable($skipUncloneable = true)
33+
{
34+
$this->skipUncloneable = $skipUncloneable;
35+
return $this;
36+
}
37+
2538
/**
2639
* Perform a deep copy of the object.
2740
* @param object $object
@@ -87,12 +100,17 @@ private function copyObject($object)
87100
return $this->hashMap[$objectHash];
88101
}
89102

90-
$newObject = clone $object;
103+
$reflectedObject = new \ReflectionObject($object);
91104

105+
if (!$reflectedObject->isCloneable() and $this->skipUncloneable) {
106+
$this->hashMap[$objectHash] = $object;
107+
return $object;
108+
}
109+
110+
$newObject = clone $object;
92111
$this->hashMap[$objectHash] = $newObject;
93112

94-
$class = new \ReflectionObject($newObject);
95-
foreach ($class->getProperties() as $property) {
113+
foreach ($reflectedObject->getProperties() as $property) {
96114
$this->copyObjectProperty($newObject, $property);
97115
}
98116

tests/DeepCopyTest/DeepCopyTest.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,14 @@ public function testDynamicProperties()
9595
$this->assertDeepCopyOf($a, $a2);
9696
}
9797

98+
public function testNonClonableItems()
99+
{
100+
$a = new \ReflectionClass('DeepCopyTest\A');
101+
$deepCopy = new DeepCopy();
102+
$a2 = $deepCopy->skipUncloneable()->copy($a);
103+
$this->assertSame($a, $a2);
104+
}
105+
98106
/**
99107
* @test
100108
*/
@@ -139,7 +147,7 @@ public function filtersShouldBeAppliedAndBreakPropertyCopying()
139147
$new = $deepCopy->copy($o);
140148

141149
$this->assertSame($o->property1, $new->property1);
142-
}
150+
}
143151
}
144152

145153
class A

0 commit comments

Comments
 (0)