diff --git a/src/DeepCopy/DeepCopy.php b/src/DeepCopy/DeepCopy.php index 920f3d9..1956de3 100755 --- a/src/DeepCopy/DeepCopy.php +++ b/src/DeepCopy/DeepCopy.php @@ -22,6 +22,19 @@ class DeepCopy */ private $filters = []; + private $skipUncloneable = false; + + /** + * Cloning uncloneable properties won't throw exception. + * @param $skipUncloneable + * @return $this + */ + public function skipUncloneable($skipUncloneable = true) + { + $this->skipUncloneable = $skipUncloneable; + return $this; + } + /** * Perform a deep copy of the object. * @param object $object @@ -87,12 +100,17 @@ private function copyObject($object) return $this->hashMap[$objectHash]; } - $newObject = clone $object; + $reflectedObject = new \ReflectionObject($object); + if (!$reflectedObject->isCloneable() and $this->skipUncloneable) { + $this->hashMap[$objectHash] = $object; + return $object; + } + + $newObject = clone $object; $this->hashMap[$objectHash] = $newObject; - $class = new \ReflectionObject($newObject); - foreach ($class->getProperties() as $property) { + foreach ($reflectedObject->getProperties() as $property) { $this->copyObjectProperty($newObject, $property); } diff --git a/tests/DeepCopyTest/DeepCopyTest.php b/tests/DeepCopyTest/DeepCopyTest.php index e21ed8b..4a3c653 100755 --- a/tests/DeepCopyTest/DeepCopyTest.php +++ b/tests/DeepCopyTest/DeepCopyTest.php @@ -95,6 +95,14 @@ public function testDynamicProperties() $this->assertDeepCopyOf($a, $a2); } + public function testNonClonableItems() + { + $a = new \ReflectionClass('DeepCopyTest\A'); + $deepCopy = new DeepCopy(); + $a2 = $deepCopy->skipUncloneable()->copy($a); + $this->assertSame($a, $a2); + } + /** * @test */ @@ -139,7 +147,7 @@ public function filtersShouldBeAppliedAndBreakPropertyCopying() $new = $deepCopy->copy($o); $this->assertSame($o->property1, $new->property1); - } + } } class A