3 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the MIT license. For more information, see
17 * <http://www.doctrine-project.org>.
20 namespace Doctrine\ORM;
22 use Doctrine\ORM\Mapping\ClassMetadata;
24 use Doctrine\Common\Collections\Collection;
25 use Doctrine\Common\Collections\ArrayCollection;
26 use Doctrine\Common\Collections\Selectable;
27 use Doctrine\Common\Collections\Criteria;
28 use Doctrine\Common\Collections\ExpressionBuilder;
33 * A PersistentCollection represents a collection of elements that have persistent state.
35 * Collections of entities represent only the associations (links) to those entities.
36 * That means, if the collection is part of a many-many mapping and you remove
37 * entities from the collection, only the links in the relation table are removed (on flush).
38 * Similarly, if you remove entities from a collection that is part of a one-many
39 * mapping this will only result in the nulling out of the foreign keys on flush.
42 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
43 * @author Roman Borschel <roman@code-factory.org>
44 * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
45 * @author Stefano Rodriguez <stefano.rodriguez@fubles.com>
46 * @todo Design for inheritance to allow custom implementations?
48 final class PersistentCollection implements Collection, Selectable
51 * A snapshot of the collection at the moment it was fetched from the database.
52 * This is used to create a diff of the collection at commit time.
56 private $snapshot = array();
59 * The entity that owns this collection.
66 * The association mapping the collection belongs to.
67 * This is currently either a OneToManyMapping or a ManyToManyMapping.
74 * The EntityManager that manages the persistence of the collection.
76 * @var \Doctrine\ORM\EntityManager
81 * The name of the field on the target entities that points to the owner
82 * of the collection. This is only set if the association is bi-directional.
86 private $backRefFieldName;
89 * The class descriptor of the collection's entity type.
94 * Whether the collection is dirty and needs to be synchronized with the database
95 * when the UnitOfWork that manages its persistent state commits.
99 private $isDirty = false;
102 * Whether the collection has already been initialized.
106 private $initialized = true;
109 * The wrapped Collection instance.
116 * Creates a new persistent collection.
118 * @param EntityManager $em The EntityManager the collection will be associated with.
119 * @param ClassMetadata $class The class descriptor of the entity type of this collection.
120 * @param array The collection elements.
122 public function __construct(EntityManager $em, $class, $coll)
126 $this->typeClass = $class;
131 * Sets the collection's owning entity together with the AssociationMapping that
132 * describes the association between the owner and the elements of the collection.
134 * @param object $entity
135 * @param AssociationMapping $assoc
137 public function setOwner($entity, array $assoc)
139 $this->owner = $entity;
140 $this->association = $assoc;
141 $this->backRefFieldName = $assoc['inversedBy'] ?: $assoc['mappedBy'];
146 * Gets the collection owner.
150 public function getOwner()
155 public function getTypeClass()
157 return $this->typeClass;
162 * Adds an element to a collection during hydration. This will automatically
163 * complete bidirectional associations in the case of a one-to-many association.
165 * @param mixed $element The element to add.
167 public function hydrateAdd($element)
169 $this->coll->add($element);
171 // If _backRefFieldName is set and its a one-to-many association,
172 // we need to set the back reference.
173 if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) {
174 // Set back reference to owner
175 $this->typeClass->reflFields[$this->backRefFieldName]->setValue(
176 $element, $this->owner
179 $this->em->getUnitOfWork()->setOriginalEntityProperty(
180 spl_object_hash($element), $this->backRefFieldName, $this->owner
187 * Sets a keyed element in the collection during hydration.
189 * @param mixed $key The key to set.
190 * $param mixed $value The element to set.
192 public function hydrateSet($key, $element)
194 $this->coll->set($key, $element);
196 // If _backRefFieldName is set, then the association is bidirectional
197 // and we need to set the back reference.
198 if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) {
199 // Set back reference to owner
200 $this->typeClass->reflFields[$this->backRefFieldName]->setValue(
201 $element, $this->owner
207 * Initializes the collection by loading its contents from the database
208 * if the collection is not yet initialized.
210 public function initialize()
212 if ($this->initialized || ! $this->association) {
216 // Has NEW objects added through add(). Remember them.
217 $newObjects = array();
219 if ($this->isDirty) {
220 $newObjects = $this->coll->toArray();
223 $this->coll->clear();
224 $this->em->getUnitOfWork()->loadCollection($this);
225 $this->takeSnapshot();
227 // Reattach NEW objects added through add(), if any.
229 foreach ($newObjects as $obj) {
230 $this->coll->add($obj);
233 $this->isDirty = true;
236 $this->initialized = true;
241 * Tells this collection to take a snapshot of its current state.
243 public function takeSnapshot()
245 $this->snapshot = $this->coll->toArray();
246 $this->isDirty = false;
251 * Returns the last snapshot of the elements in the collection.
253 * @return array The last snapshot of the elements.
255 public function getSnapshot()
257 return $this->snapshot;
266 public function getDeleteDiff()
268 return array_udiff_assoc(
270 $this->coll->toArray(),
271 function($a, $b) { return $a === $b ? 0 : 1; }
281 public function getInsertDiff()
283 return array_udiff_assoc(
284 $this->coll->toArray(),
286 function($a, $b) { return $a === $b ? 0 : 1; }
291 * INTERNAL: Gets the association mapping of the collection.
295 public function getMapping()
297 return $this->association;
301 * Marks this collection as changed/dirty.
303 private function changed()
305 if ($this->isDirty) {
309 $this->isDirty = true;
311 if ($this->association !== null &&
312 $this->association['isOwningSide'] &&
313 $this->association['type'] === ClassMetadata::MANY_TO_MANY &&
315 $this->em->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify()) {
316 $this->em->getUnitOfWork()->scheduleForDirtyCheck($this->owner);
321 * Gets a boolean flag indicating whether this collection is dirty which means
322 * its state needs to be synchronized with the database.
324 * @return boolean TRUE if the collection is dirty, FALSE otherwise.
326 public function isDirty()
328 return $this->isDirty;
332 * Sets a boolean flag, indicating whether this collection is dirty.
334 * @param boolean $dirty Whether the collection should be marked dirty or not.
336 public function setDirty($dirty)
338 $this->isDirty = $dirty;
342 * Sets the initialized flag of the collection, forcing it into that state.
344 * @param boolean $bool
346 public function setInitialized($bool)
348 $this->initialized = $bool;
352 * Checks whether this collection has been initialized.
356 public function isInitialized()
358 return $this->initialized;
362 public function first()
366 return $this->coll->first();
370 public function last()
374 return $this->coll->last();
380 public function remove($key)
382 // TODO: If the keys are persistent as well (not yet implemented)
383 // and the collection is not initialized and orphanRemoval is
384 // not used we can issue a straight SQL delete/update on the
385 // association (table). Without initializing the collection.
388 $removed = $this->coll->remove($key);
396 if ($this->association !== null &&
397 $this->association['type'] & ClassMetadata::TO_MANY &&
399 $this->association['orphanRemoval']) {
400 $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed);
409 public function removeElement($element)
411 if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
412 if ($this->coll->contains($element)) {
413 return $this->coll->removeElement($element);
416 $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
418 if ($persister->removeElement($this, $element)) {
427 $removed = $this->coll->removeElement($element);
435 if ($this->association !== null &&
436 $this->association['type'] & ClassMetadata::TO_MANY &&
438 $this->association['orphanRemoval']) {
439 $this->em->getUnitOfWork()->scheduleOrphanRemoval($element);
448 public function containsKey($key)
452 return $this->coll->containsKey($key);
458 public function contains($element)
460 if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
461 $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
463 return $this->coll->contains($element) || $persister->contains($this, $element);
468 return $this->coll->contains($element);
474 public function exists(Closure $p)
478 return $this->coll->exists($p);
484 public function indexOf($element)
488 return $this->coll->indexOf($element);
494 public function get($key)
498 return $this->coll->get($key);
504 public function getKeys()
508 return $this->coll->getKeys();
514 public function getValues()
518 return $this->coll->getValues();
524 public function count()
526 if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
527 $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
529 return $persister->count($this) + ($this->isDirty ? $this->coll->count() : 0);
534 return $this->coll->count();
540 public function set($key, $value)
544 $this->coll->set($key, $value);
552 public function add($value)
554 $this->coll->add($value);
564 public function isEmpty()
568 return $this->coll->isEmpty();
574 public function getIterator()
578 return $this->coll->getIterator();
584 public function map(Closure $func)
588 return $this->coll->map($func);
594 public function filter(Closure $p)
598 return $this->coll->filter($p);
604 public function forAll(Closure $p)
608 return $this->coll->forAll($p);
614 public function partition(Closure $p)
618 return $this->coll->partition($p);
624 public function toArray()
628 return $this->coll->toArray();
634 public function clear()
636 if ($this->initialized && $this->isEmpty()) {
640 $uow = $this->em->getUnitOfWork();
642 if ($this->association['type'] & ClassMetadata::TO_MANY &&
643 $this->association['orphanRemoval'] &&
645 // we need to initialize here, as orphan removal acts like implicit cascadeRemove,
646 // hence for event listeners we need the objects in memory.
649 foreach ($this->coll as $element) {
650 $uow->scheduleOrphanRemoval($element);
654 $this->coll->clear();
656 $this->initialized = true; // direct call, {@link initialize()} is too expensive
658 if ($this->association['isOwningSide']) {
661 $uow->scheduleCollectionDeletion($this);
663 $this->takeSnapshot();
668 * Called by PHP when this collection is serialized. Ensures that only the
669 * elements are properly serialized.
671 * @internal Tried to implement Serializable first but that did not work well
672 * with circular references. This solution seems simpler and works well.
674 public function __sleep()
676 return array('coll', 'initialized');
679 /* ArrayAccess implementation */
684 public function offsetExists($offset)
686 return $this->containsKey($offset);
692 public function offsetGet($offset)
694 return $this->get($offset);
701 public function offsetSet($offset, $value)
703 if ( ! isset($offset)) {
704 return $this->add($value);
707 return $this->set($offset, $value);
713 public function offsetUnset($offset)
715 return $this->remove($offset);
718 public function key()
720 return $this->coll->key();
724 * Gets the element of the collection at the current iterator position.
726 public function current()
728 return $this->coll->current();
732 * Moves the internal iterator position to the next element.
734 public function next()
736 return $this->coll->next();
740 * Retrieves the wrapped Collection instance.
742 * @return \Doctrine\Common\Collections\Collection
744 public function unwrap()
750 * Extract a slice of $length elements starting at position $offset from the Collection.
752 * If $length is null it returns all elements from $offset to the end of the Collection.
753 * Keys have to be preserved by this method. Calling this method will only return the
754 * selected slice and NOT change the elements contained in the collection slice is called on.
761 public function slice($offset, $length = null)
763 if ( ! $this->initialized && ! $this->isDirty && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
764 $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
766 return $persister->slice($this, $offset, $length);
771 return $this->coll->slice($offset, $length);
775 * Cleanup internal state of cloned persistent collection.
777 * The following problems have to be prevented:
778 * 1. Added entities are added to old PC
779 * 2. New collection is not dirty, if reused on other entity nothing
781 * 3. Snapshot leads to invalid diffs being generated.
782 * 4. Lazy loading grabs entities from old owner object.
783 * 5. New collection is connected to old owner and leads to duplicate keys.
785 public function __clone()
787 if (is_object($this->coll)) {
788 $this->coll = clone $this->coll;
794 $this->snapshot = array();
800 * Select all elements from a selectable that match the expression and
801 * return a new collection containing these elements.
803 * @param \Doctrine\Common\Collections\Criteria $criteria
806 public function matching(Criteria $criteria)
808 if ($this->initialized) {
809 return $this->coll->matching($criteria);
812 if ($this->association['type'] !== ClassMetadata::ONE_TO_MANY) {
813 throw new \RuntimeException("Matching Criteria on PersistentCollection only works on OneToMany assocations at the moment.");
816 // If there are NEW objects we have to check if any of them matches the criteria
817 $newObjects = array();
819 if ($this->isDirty) {
820 $newObjects = $this->coll->matching($criteria)->toArray();
823 $targetClass = $this->em->getClassMetadata(get_class($this->owner));
825 $id = $targetClass->getSingleIdReflectionProperty()->getValue($this->owner);
826 $builder = Criteria::expr();
827 $ownerExpression = $builder->eq($this->backRefFieldName, $id);
828 $expression = $criteria->getWhereExpression();
829 $expression = $expression ? $builder->andX($expression, $ownerExpression) : $ownerExpression;
831 $criteria->where($expression);
833 $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']);
835 return new ArrayCollection(array_merge($persister->loadCriteria($criteria), $newObjects));