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\Common\Collections\AbstractLazyCollection
;
23 use Doctrine\Common\Collections\Collection
;
24 use Doctrine\Common\Collections\ArrayCollection
;
25 use Doctrine\Common\Collections\Selectable
;
26 use Doctrine\Common\Collections\Criteria
;
27 use Doctrine\ORM\Mapping\ClassMetadata
;
28 use Doctrine\ORM\Mapping\ClassMetadataInfo
;
31 * A PersistentCollection represents a collection of elements that have persistent state.
33 * Collections of entities represent only the associations (links) to those entities.
34 * That means, if the collection is part of a many-many mapping and you remove
35 * entities from the collection, only the links in the relation table are removed (on flush).
36 * Similarly, if you remove entities from a collection that is part of a one-many
37 * mapping this will only result in the nulling out of the foreign keys on flush.
40 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
41 * @author Roman Borschel <roman@code-factory.org>
42 * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
43 * @author Stefano Rodriguez <stefano.rodriguez@fubles.com>
45 final class PersistentCollection
extends AbstractLazyCollection
implements Selectable
48 * A snapshot of the collection at the moment it was fetched from the database.
49 * This is used to create a diff of the collection at commit time.
53 private $snapshot = array();
56 * The entity that owns this collection.
63 * The association mapping the collection belongs to.
64 * This is currently either a OneToManyMapping or a ManyToManyMapping.
71 * The EntityManager that manages the persistence of the collection.
73 * @var \Doctrine\ORM\EntityManagerInterface
78 * The name of the field on the target entities that points to the owner
79 * of the collection. This is only set if the association is bi-directional.
83 private $backRefFieldName;
86 * The class descriptor of the collection's entity type.
93 * Whether the collection is dirty and needs to be synchronized with the database
94 * when the UnitOfWork that manages its persistent state commits.
98 private $isDirty = false;
101 * Creates a new persistent collection.
103 * @param EntityManagerInterface $em The EntityManager the collection will be associated with.
104 * @param ClassMetadata $class The class descriptor of the entity type of this collection.
105 * @param Collection $collection The collection elements.
107 public function __construct(EntityManagerInterface
$em, $class, Collection
$collection)
109 $this->collection
= $collection;
111 $this->typeClass
= $class;
112 $this->initialized
= true;
117 * Sets the collection's owning entity together with the AssociationMapping that
118 * describes the association between the owner and the elements of the collection.
120 * @param object $entity
121 * @param array $assoc
125 public function setOwner($entity, array $assoc)
127 $this->owner
= $entity;
128 $this->association
= $assoc;
129 $this->backRefFieldName
= $assoc['inversedBy'] ?
: $assoc['mappedBy'];
134 * Gets the collection owner.
138 public function getOwner()
144 * @return Mapping\ClassMetadata
146 public function getTypeClass()
148 return $this->typeClass
;
153 * Adds an element to a collection during hydration. This will automatically
154 * complete bidirectional associations in the case of a one-to-many association.
156 * @param mixed $element The element to add.
160 public function hydrateAdd($element)
162 $this->collection
->add($element);
164 // If _backRefFieldName is set and its a one-to-many association,
165 // we need to set the back reference.
166 if ($this->backRefFieldName
&& $this->association
['type'] === ClassMetadata
::ONE_TO_MANY
) {
167 // Set back reference to owner
168 $this->typeClass
->reflFields
[$this->backRefFieldName
]->setValue(
169 $element, $this->owner
172 $this->em
->getUnitOfWork()->setOriginalEntityProperty(
173 spl_object_hash($element), $this->backRefFieldName
, $this->owner
180 * Sets a keyed element in the collection during hydration.
182 * @param mixed $key The key to set.
183 * @param mixed $element The element to set.
187 public function hydrateSet($key, $element)
189 $this->collection
->set($key, $element);
191 // If _backRefFieldName is set, then the association is bidirectional
192 // and we need to set the back reference.
193 if ($this->backRefFieldName
&& $this->association
['type'] === ClassMetadata
::ONE_TO_MANY
) {
194 // Set back reference to owner
195 $this->typeClass
->reflFields
[$this->backRefFieldName
]->setValue(
196 $element, $this->owner
202 * Initializes the collection by loading its contents from the database
203 * if the collection is not yet initialized.
207 public function initialize()
209 if ($this->initialized ||
! $this->association
) {
213 $this->doInitialize();
215 $this->initialized
= true;
220 * Tells this collection to take a snapshot of its current state.
224 public function takeSnapshot()
226 $this->snapshot
= $this->collection
->toArray();
227 $this->isDirty
= false;
232 * Returns the last snapshot of the elements in the collection.
234 * @return array The last snapshot of the elements.
236 public function getSnapshot()
238 return $this->snapshot
;
247 public function getDeleteDiff()
249 return array_udiff_assoc(
251 $this->collection
->toArray(),
252 function($a, $b) { return $a === $b ?
0 : 1; }
262 public function getInsertDiff()
264 return array_udiff_assoc(
265 $this->collection
->toArray(),
267 function($a, $b) { return $a === $b ?
0 : 1; }
272 * INTERNAL: Gets the association mapping of the collection.
276 public function getMapping()
278 return $this->association
;
282 * Marks this collection as changed/dirty.
286 private function changed()
288 if ($this->isDirty
) {
292 $this->isDirty
= true;
294 if ($this->association
!== null &&
295 $this->association
['isOwningSide'] &&
296 $this->association
['type'] === ClassMetadata
::MANY_TO_MANY
&&
298 $this->em
->getClassMetadata(get_class($this->owner
))->isChangeTrackingNotify()) {
299 $this->em
->getUnitOfWork()->scheduleForDirtyCheck($this->owner
);
304 * Gets a boolean flag indicating whether this collection is dirty which means
305 * its state needs to be synchronized with the database.
307 * @return boolean TRUE if the collection is dirty, FALSE otherwise.
309 public function isDirty()
311 return $this->isDirty
;
315 * Sets a boolean flag, indicating whether this collection is dirty.
317 * @param boolean $dirty Whether the collection should be marked dirty or not.
321 public function setDirty($dirty)
323 $this->isDirty
= $dirty;
327 * Sets the initialized flag of the collection, forcing it into that state.
329 * @param boolean $bool
333 public function setInitialized($bool)
335 $this->initialized
= $bool;
341 public function remove($key)
343 // TODO: If the keys are persistent as well (not yet implemented)
344 // and the collection is not initialized and orphanRemoval is
345 // not used we can issue a straight SQL delete/update on the
346 // association (table). Without initializing the collection.
347 $removed = parent
::remove($key);
355 if ($this->association
!== null &&
356 $this->association
['type'] & ClassMetadata
::TO_MANY
&&
358 $this->association
['orphanRemoval']) {
359 $this->em
->getUnitOfWork()->scheduleOrphanRemoval($removed);
368 public function removeElement($element)
370 if ( ! $this->initialized
&& $this->association
['fetch'] === Mapping\ClassMetadataInfo
::FETCH_EXTRA_LAZY
) {
371 if ($this->collection
->contains($element)) {
372 return $this->collection
->removeElement($element);
375 $persister = $this->em
->getUnitOfWork()->getCollectionPersister($this->association
);
377 return $persister->removeElement($this, $element);
380 $removed = parent
::removeElement($element);
388 if ($this->association
!== null &&
389 $this->association
['type'] & ClassMetadata
::TO_MANY
&&
391 $this->association
['orphanRemoval']) {
392 $this->em
->getUnitOfWork()->scheduleOrphanRemoval($element);
401 public function containsKey($key)
403 if (! $this->initialized
&& $this->association
['fetch'] === Mapping\ClassMetadataInfo
::FETCH_EXTRA_LAZY
404 && isset($this->association
['indexBy'])) {
405 $persister = $this->em
->getUnitOfWork()->getCollectionPersister($this->association
);
407 return $this->collection
->containsKey($key) ||
$persister->containsKey($this, $key);
410 return parent
::containsKey($key);
416 public function contains($element)
418 if ( ! $this->initialized
&& $this->association
['fetch'] === Mapping\ClassMetadataInfo
::FETCH_EXTRA_LAZY
) {
419 $persister = $this->em
->getUnitOfWork()->getCollectionPersister($this->association
);
421 return $this->collection
->contains($element) ||
$persister->contains($this, $element);
424 return parent
::contains($element);
430 public function get($key)
432 if ( ! $this->initialized
433 && $this->association
['fetch'] === Mapping\ClassMetadataInfo
::FETCH_EXTRA_LAZY
434 && isset($this->association
['indexBy'])
436 if (!$this->typeClass
->isIdentifierComposite
&& $this->typeClass
->isIdentifier($this->association
['indexBy'])) {
437 return $this->em
->find($this->typeClass
->name
, $key);
440 return $this->em
->getUnitOfWork()->getCollectionPersister($this->association
)->get($this, $key);
443 return parent
::get($key);
449 public function count()
451 if ( ! $this->initialized
&& $this->association
['fetch'] === Mapping\ClassMetadataInfo
::FETCH_EXTRA_LAZY
) {
452 $persister = $this->em
->getUnitOfWork()->getCollectionPersister($this->association
);
454 return $persister->count($this) +
($this->isDirty ?
$this->collection
->count() : 0);
457 return parent
::count();
463 public function set($key, $value)
465 parent
::set($key, $value);
473 public function add($value)
475 $this->collection
->add($value);
482 /* ArrayAccess implementation */
487 public function offsetExists($offset)
489 return $this->containsKey($offset);
495 public function offsetGet($offset)
497 return $this->get($offset);
503 public function offsetSet($offset, $value)
505 if ( ! isset($offset)) {
506 return $this->add($value);
509 return $this->set($offset, $value);
515 public function offsetUnset($offset)
517 return $this->remove($offset);
523 public function isEmpty()
525 return $this->collection
->isEmpty() && $this->count() === 0;
531 public function clear()
533 if ($this->initialized
&& $this->isEmpty()) {
534 $this->collection
->clear();
539 $uow = $this->em
->getUnitOfWork();
541 if ($this->association
['type'] & ClassMetadata
::TO_MANY
&&
542 $this->association
['orphanRemoval'] &&
544 // we need to initialize here, as orphan removal acts like implicit cascadeRemove,
545 // hence for event listeners we need the objects in memory.
548 foreach ($this->collection
as $element) {
549 $uow->scheduleOrphanRemoval($element);
553 $this->collection
->clear();
555 $this->initialized
= true; // direct call, {@link initialize()} is too expensive
557 if ($this->association
['isOwningSide'] && $this->owner
) {
560 $uow->scheduleCollectionDeletion($this);
562 $this->takeSnapshot();
567 * Called by PHP when this collection is serialized. Ensures that only the
568 * elements are properly serialized.
570 * Internal note: Tried to implement Serializable first but that did not work well
571 * with circular references. This solution seems simpler and works well.
575 public function __sleep()
577 return array('collection', 'initialized');
581 * Extracts a slice of $length elements starting at position $offset from the Collection.
583 * If $length is null it returns all elements from $offset to the end of the Collection.
584 * Keys have to be preserved by this method. Calling this method will only return the
585 * selected slice and NOT change the elements contained in the collection slice is called on.
588 * @param int|null $length
592 public function slice($offset, $length = null)
594 if ( ! $this->initialized
&& ! $this->isDirty
&& $this->association
['fetch'] === Mapping\ClassMetadataInfo
::FETCH_EXTRA_LAZY
) {
595 $persister = $this->em
->getUnitOfWork()->getCollectionPersister($this->association
);
597 return $persister->slice($this, $offset, $length);
600 return parent
::slice($offset, $length);
604 * Cleans up internal state of cloned persistent collection.
606 * The following problems have to be prevented:
607 * 1. Added entities are added to old PC
608 * 2. New collection is not dirty, if reused on other entity nothing
610 * 3. Snapshot leads to invalid diffs being generated.
611 * 4. Lazy loading grabs entities from old owner object.
612 * 5. New collection is connected to old owner and leads to duplicate keys.
616 public function __clone()
618 if (is_object($this->collection
)) {
619 $this->collection
= clone $this->collection
;
625 $this->snapshot
= array();
631 * Selects all elements from a selectable that match the expression and
632 * return a new collection containing these elements.
634 * @param \Doctrine\Common\Collections\Criteria $criteria
638 * @throws \RuntimeException
640 public function matching(Criteria
$criteria)
642 if ($this->isDirty
) {
646 if ($this->initialized
) {
647 return $this->collection
->matching($criteria);
650 if ($this->association
['type'] === ClassMetadata
::MANY_TO_MANY
) {
651 $persister = $this->em
->getUnitOfWork()->getCollectionPersister($this->association
);
653 return new ArrayCollection($persister->loadCriteria($this, $criteria));
656 $builder = Criteria
::expr();
657 $ownerExpression = $builder->eq($this->backRefFieldName
, $this->owner
);
658 $expression = $criteria->getWhereExpression();
659 $expression = $expression ?
$builder->andX($expression, $ownerExpression) : $ownerExpression;
661 $criteria = clone $criteria;
662 $criteria->where($expression);
664 $persister = $this->em
->getUnitOfWork()->getEntityPersister($this->association
['targetEntity']);
666 return ($this->association
['fetch'] === ClassMetadataInfo
::FETCH_EXTRA_LAZY
)
667 ?
new LazyCriteriaCollection($persister, $criteria)
668 : new ArrayCollection($persister->loadCriteria($criteria));
672 * Retrieves the wrapped Collection instance.
674 * @return \Doctrine\Common\Collections\Collection
676 public function unwrap()
678 return $this->collection
;
684 protected function doInitialize()
686 // Has NEW objects added through add(). Remember them.
687 $newlyAddedDirtyObjects = array();
689 if ($this->isDirty
) {
690 $newlyAddedDirtyObjects = $this->collection
->toArray();
693 $this->collection
->clear();
694 $this->em
->getUnitOfWork()->loadCollection($this);
695 $this->takeSnapshot();
697 if ($newlyAddedDirtyObjects) {
698 $this->restoreNewObjectsInDirtyCollection($newlyAddedDirtyObjects);
703 * @param object[] $newObjects
707 * Note: the only reason why this entire looping/complexity is performed via `spl_object_hash`
708 * is because we want to prevent using `array_udiff()`, which is likely to cause very
709 * high overhead (complexity of O(n^2)). `array_diff_key()` performs the operation in
710 * core, which is faster than using a callback for comparisons
712 private function restoreNewObjectsInDirtyCollection(array $newObjects)
714 $loadedObjects = $this->collection
->toArray();
715 $newObjectsByOid = \array_combine
(\array_map
('spl_object_hash', $newObjects), $newObjects);
716 $loadedObjectsByOid = \array_combine
(\array_map
('spl_object_hash', $loadedObjects), $loadedObjects);
717 $newObjectsThatWereNotLoaded = \array_diff_key
($newObjectsByOid, $loadedObjectsByOid);
719 if ($newObjectsThatWereNotLoaded) {
720 // Reattach NEW objects added through add(), if any.
721 \array_walk
($newObjectsThatWereNotLoaded, [$this->collection
, 'add']);
723 $this->isDirty
= true;