Skip to content

Instantly share code, notes, and snippets.

@mmoreram
Last active December 19, 2015 22:38
Show Gist options
  • Save mmoreram/6028286 to your computer and use it in GitHub Desktop.
Save mmoreram/6028286 to your computer and use it in GitHub Desktop.
<?php
/**
* Custom ArrayCollection for Doctrine2 entities
*/
namespace XXX\XXX\Collections;
/**
* Custom array collection
*
* Entity is only inserted once
*/
class EntityArrayCollection extends ArrayCollection
{
/**
* We just add value if not already exists
*
* If two elements are already mapped, so both have id, are equal if both ids are equal
*
* Otherwise, two elements are equal if are same object without id ( same memory position )
*
* {@inheritDoc}
*/
public function add($value)
{
if ($this->forAll(function($key, $element) use ($value) {
if ($element->getId() && $value->getId()) {
return $element->getId() !== $value->getId();
}
return spl_object_hash($element) !== spl_object_hash($value);
})) {
parent::add($value);
}
return $this;
}
/**
* We just remove element when exists inside collection
*
* If two elements are already mapped, so both have id, are equal if both ids are equal
*
* Otherwise, two elements are equal if are same object without id ( same memory position )
*
* {@inheritDoc}
*/
public function removeElement($value)
{
foreach ($this as $key => $element) {
if ($element->getId() && $value->getId()) {
if ($element->getId() === $value->getId()) {
$this->remove($key);
break;
}
} else {
if (spl_object_hash($element) === spl_object_hash($value)) {
$this->remove($key);
break;
}
}
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment