Created
June 24, 2014 19:43
-
-
Save johnkary/390d3ce10214a1eb45d9 to your computer and use it in GitHub Desktop.
Doctrine ArrayCollection ->toArray() usage modifies original array in collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Doctrine\Common\Collections\ArrayCollection; | |
class ArrayCollectionTest extends \PHPUnit_Framework_TestCase | |
{ | |
public function testModifiesOriginalCollection() | |
{ | |
$data = array( | |
1 => new Destination(), | |
2 => new Destination(), | |
3 => new Destination(), | |
); | |
$collection = new ArrayCollection($data); | |
/** @var Destination $destination */ | |
foreach ($collection->toArray() as $key => $destination) { | |
if (0 === ($key % 2)) { | |
$destination->setEnabled(false); | |
} | |
} | |
// Collection exposes its internal $this->_elements array, so changes to | |
// ->toArray() values are reflected in the original Collection | |
/** @var Destination $d */ | |
foreach ($collection as $k => $d) { | |
$this->assertTrue($d->isEnabled(), sprintf("Destination %d is disabled when we expected it to be enabled", $k)); | |
} | |
} | |
} | |
class Destination | |
{ | |
// Defaults true! | |
private $enabled = true; | |
public function setEnabled($bool) { | |
$this->enabled = $bool; | |
} | |
public function isEnabled() { | |
return $this->enabled; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment