Skip to content

Instantly share code, notes, and snippets.

@johnkary
Created June 24, 2014 19:43
Show Gist options
  • Save johnkary/390d3ce10214a1eb45d9 to your computer and use it in GitHub Desktop.
Save johnkary/390d3ce10214a1eb45d9 to your computer and use it in GitHub Desktop.
Doctrine ArrayCollection ->toArray() usage modifies original array in collection
<?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