Skip to content

Commit

Permalink
Merge pull request #2 from DavertMik/master
Browse files Browse the repository at this point in the history
Fixed cloning non-clonable items
  • Loading branch information
mnapoli committed Mar 21, 2014
2 parents 1ee5325 + 6247d82 commit 804c17d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
24 changes: 21 additions & 3 deletions src/DeepCopy/DeepCopy.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}

Expand Down
10 changes: 9 additions & 1 deletion tests/DeepCopyTest/DeepCopyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -139,7 +147,7 @@ public function filtersShouldBeAppliedAndBreakPropertyCopying()
$new = $deepCopy->copy($o);

$this->assertSame($o->property1, $new->property1);
}
}
}

class A
Expand Down

0 comments on commit 804c17d

Please sign in to comment.