vendor/doctrine/orm/lib/Doctrine/ORM/PersistentCollection.php line 54

Open in your IDE?
  1. <?php
  2. /*
  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.
  14.  *
  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>.
  18.  */
  19. namespace Doctrine\ORM;
  20. use Doctrine\Common\Collections\AbstractLazyCollection;
  21. use Doctrine\Common\Collections\ArrayCollection;
  22. use Doctrine\Common\Collections\Collection;
  23. use Doctrine\Common\Collections\Criteria;
  24. use Doctrine\Common\Collections\Selectable;
  25. use Doctrine\ORM\Mapping\ClassMetadata;
  26. use RuntimeException;
  27. use function array_combine;
  28. use function array_diff_key;
  29. use function array_map;
  30. use function array_udiff_assoc;
  31. use function array_walk;
  32. use function get_class;
  33. use function is_object;
  34. use function spl_object_hash;
  35. /**
  36.  * A PersistentCollection represents a collection of elements that have persistent state.
  37.  *
  38.  * Collections of entities represent only the associations (links) to those entities.
  39.  * That means, if the collection is part of a many-many mapping and you remove
  40.  * entities from the collection, only the links in the relation table are removed (on flush).
  41.  * Similarly, if you remove entities from a collection that is part of a one-many
  42.  * mapping this will only result in the nulling out of the foreign keys on flush.
  43.  *
  44.  * @phpstan-template TKey
  45.  * @psalm-template TKey of array-key
  46.  * @psalm-template T
  47.  * @template-implements Collection<TKey,T>
  48.  */
  49. final class PersistentCollection extends AbstractLazyCollection implements Selectable
  50. {
  51.     /**
  52.      * A snapshot of the collection at the moment it was fetched from the database.
  53.      * This is used to create a diff of the collection at commit time.
  54.      *
  55.      * @psalm-var array<string|int, mixed>
  56.      */
  57.     private $snapshot = [];
  58.     /**
  59.      * The entity that owns this collection.
  60.      *
  61.      * @var object|null
  62.      */
  63.     private $owner;
  64.     /**
  65.      * The association mapping the collection belongs to.
  66.      * This is currently either a OneToManyMapping or a ManyToManyMapping.
  67.      *
  68.      * @psalm-var array<string, mixed>|null
  69.      */
  70.     private $association;
  71.     /**
  72.      * The EntityManager that manages the persistence of the collection.
  73.      *
  74.      * @var EntityManagerInterface
  75.      */
  76.     private $em;
  77.     /**
  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.
  80.      *
  81.      * @var string
  82.      */
  83.     private $backRefFieldName;
  84.     /**
  85.      * The class descriptor of the collection's entity type.
  86.      *
  87.      * @var ClassMetadata
  88.      */
  89.     private $typeClass;
  90.     /**
  91.      * Whether the collection is dirty and needs to be synchronized with the database
  92.      * when the UnitOfWork that manages its persistent state commits.
  93.      *
  94.      * @var bool
  95.      */
  96.     private $isDirty false;
  97.     /**
  98.      * Creates a new persistent collection.
  99.      *
  100.      * @param EntityManagerInterface $em    The EntityManager the collection will be associated with.
  101.      * @param ClassMetadata          $class The class descriptor of the entity type of this collection.
  102.      * @psalm-param Collection<TKey, T> $collection The collection elements.
  103.      */
  104.     public function __construct(EntityManagerInterface $em$classCollection $collection)
  105.     {
  106.         $this->collection  $collection;
  107.         $this->em          $em;
  108.         $this->typeClass   $class;
  109.         $this->initialized true;
  110.     }
  111.     /**
  112.      * INTERNAL:
  113.      * Sets the collection's owning entity together with the AssociationMapping that
  114.      * describes the association between the owner and the elements of the collection.
  115.      *
  116.      * @param object $entity
  117.      * @psalm-param array<string, mixed> $assoc
  118.      */
  119.     public function setOwner($entity, array $assoc): void
  120.     {
  121.         $this->owner            $entity;
  122.         $this->association      $assoc;
  123.         $this->backRefFieldName $assoc['inversedBy'] ?: $assoc['mappedBy'];
  124.     }
  125.     /**
  126.      * INTERNAL:
  127.      * Gets the collection owner.
  128.      *
  129.      * @return object|null
  130.      */
  131.     public function getOwner()
  132.     {
  133.         return $this->owner;
  134.     }
  135.     /**
  136.      * @return Mapping\ClassMetadata
  137.      */
  138.     public function getTypeClass(): Mapping\ClassMetadataInfo
  139.     {
  140.         return $this->typeClass;
  141.     }
  142.     /**
  143.      * INTERNAL:
  144.      * Adds an element to a collection during hydration. This will automatically
  145.      * complete bidirectional associations in the case of a one-to-many association.
  146.      *
  147.      * @param mixed $element The element to add.
  148.      */
  149.     public function hydrateAdd($element): void
  150.     {
  151.         $this->collection->add($element);
  152.         // If _backRefFieldName is set and its a one-to-many association,
  153.         // we need to set the back reference.
  154.         if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) {
  155.             // Set back reference to owner
  156.             $this->typeClass->reflFields[$this->backRefFieldName]->setValue(
  157.                 $element,
  158.                 $this->owner
  159.             );
  160.             $this->em->getUnitOfWork()->setOriginalEntityProperty(
  161.                 spl_object_hash($element),
  162.                 $this->backRefFieldName,
  163.                 $this->owner
  164.             );
  165.         }
  166.     }
  167.     /**
  168.      * INTERNAL:
  169.      * Sets a keyed element in the collection during hydration.
  170.      *
  171.      * @param mixed $key     The key to set.
  172.      * @param mixed $element The element to set.
  173.      */
  174.     public function hydrateSet($key$element): void
  175.     {
  176.         $this->collection->set($key$element);
  177.         // If _backRefFieldName is set, then the association is bidirectional
  178.         // and we need to set the back reference.
  179.         if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) {
  180.             // Set back reference to owner
  181.             $this->typeClass->reflFields[$this->backRefFieldName]->setValue(
  182.                 $element,
  183.                 $this->owner
  184.             );
  185.         }
  186.     }
  187.     /**
  188.      * Initializes the collection by loading its contents from the database
  189.      * if the collection is not yet initialized.
  190.      */
  191.     public function initialize(): void
  192.     {
  193.         if ($this->initialized || ! $this->association) {
  194.             return;
  195.         }
  196.         $this->doInitialize();
  197.         $this->initialized true;
  198.     }
  199.     /**
  200.      * INTERNAL:
  201.      * Tells this collection to take a snapshot of its current state.
  202.      */
  203.     public function takeSnapshot(): void
  204.     {
  205.         $this->snapshot $this->collection->toArray();
  206.         $this->isDirty  false;
  207.     }
  208.     /**
  209.      * INTERNAL:
  210.      * Returns the last snapshot of the elements in the collection.
  211.      *
  212.      * @psalm-return array<string|int, mixed> The last snapshot of the elements.
  213.      */
  214.     public function getSnapshot(): array
  215.     {
  216.         return $this->snapshot;
  217.     }
  218.     /**
  219.      * INTERNAL:
  220.      * getDeleteDiff
  221.      *
  222.      * @return mixed[]
  223.      */
  224.     public function getDeleteDiff(): array
  225.     {
  226.         return array_udiff_assoc(
  227.             $this->snapshot,
  228.             $this->collection->toArray(),
  229.             static function ($a$b): int {
  230.                 return $a === $b 1;
  231.             }
  232.         );
  233.     }
  234.     /**
  235.      * INTERNAL:
  236.      * getInsertDiff
  237.      *
  238.      * @return mixed[]
  239.      */
  240.     public function getInsertDiff(): array
  241.     {
  242.         return array_udiff_assoc(
  243.             $this->collection->toArray(),
  244.             $this->snapshot,
  245.             static function ($a$b): int {
  246.                 return $a === $b 1;
  247.             }
  248.         );
  249.     }
  250.     /**
  251.      * INTERNAL: Gets the association mapping of the collection.
  252.      *
  253.      * @psalm-return array<string, mixed>|null
  254.      */
  255.     public function getMapping(): ?array
  256.     {
  257.         return $this->association;
  258.     }
  259.     /**
  260.      * Marks this collection as changed/dirty.
  261.      */
  262.     private function changed(): void
  263.     {
  264.         if ($this->isDirty) {
  265.             return;
  266.         }
  267.         $this->isDirty true;
  268.         if (
  269.             $this->association !== null &&
  270.             $this->association['isOwningSide'] &&
  271.             $this->association['type'] === ClassMetadata::MANY_TO_MANY &&
  272.             $this->owner &&
  273.             $this->em->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify()
  274.         ) {
  275.             $this->em->getUnitOfWork()->scheduleForDirtyCheck($this->owner);
  276.         }
  277.     }
  278.     /**
  279.      * Gets a boolean flag indicating whether this collection is dirty which means
  280.      * its state needs to be synchronized with the database.
  281.      *
  282.      * @return bool TRUE if the collection is dirty, FALSE otherwise.
  283.      */
  284.     public function isDirty(): bool
  285.     {
  286.         return $this->isDirty;
  287.     }
  288.     /**
  289.      * Sets a boolean flag, indicating whether this collection is dirty.
  290.      *
  291.      * @param bool $dirty Whether the collection should be marked dirty or not.
  292.      */
  293.     public function setDirty($dirty): void
  294.     {
  295.         $this->isDirty $dirty;
  296.     }
  297.     /**
  298.      * Sets the initialized flag of the collection, forcing it into that state.
  299.      *
  300.      * @param bool $bool
  301.      */
  302.     public function setInitialized($bool): void
  303.     {
  304.         $this->initialized $bool;
  305.     }
  306.     /**
  307.      * {@inheritdoc}
  308.      *
  309.      * @return object
  310.      */
  311.     public function remove($key)
  312.     {
  313.         // TODO: If the keys are persistent as well (not yet implemented)
  314.         //       and the collection is not initialized and orphanRemoval is
  315.         //       not used we can issue a straight SQL delete/update on the
  316.         //       association (table). Without initializing the collection.
  317.         $removed parent::remove($key);
  318.         if (! $removed) {
  319.             return $removed;
  320.         }
  321.         $this->changed();
  322.         if (
  323.             $this->association !== null &&
  324.             $this->association['type'] & ClassMetadata::TO_MANY &&
  325.             $this->owner &&
  326.             $this->association['orphanRemoval']
  327.         ) {
  328.             $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed);
  329.         }
  330.         return $removed;
  331.     }
  332.     /**
  333.      * {@inheritdoc}
  334.      */
  335.     public function removeElement($element): bool
  336.     {
  337.         $removed parent::removeElement($element);
  338.         if (! $removed) {
  339.             return $removed;
  340.         }
  341.         $this->changed();
  342.         if (
  343.             $this->association !== null &&
  344.             $this->association['type'] & ClassMetadata::TO_MANY &&
  345.             $this->owner &&
  346.             $this->association['orphanRemoval']
  347.         ) {
  348.             $this->em->getUnitOfWork()->scheduleOrphanRemoval($element);
  349.         }
  350.         return $removed;
  351.     }
  352.     /**
  353.      * {@inheritdoc}
  354.      */
  355.     public function containsKey($key): bool
  356.     {
  357.         if (
  358.             ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY
  359.             && isset($this->association['indexBy'])
  360.         ) {
  361.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  362.             return $this->collection->containsKey($key) || $persister->containsKey($this$key);
  363.         }
  364.         return parent::containsKey($key);
  365.     }
  366.     /**
  367.      * {@inheritdoc}
  368.      */
  369.     public function contains($element): bool
  370.     {
  371.         if (! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) {
  372.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  373.             return $this->collection->contains($element) || $persister->contains($this$element);
  374.         }
  375.         return parent::contains($element);
  376.     }
  377.     /**
  378.      * {@inheritdoc}
  379.      */
  380.     public function get($key)
  381.     {
  382.         if (
  383.             ! $this->initialized
  384.             && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY
  385.             && isset($this->association['indexBy'])
  386.         ) {
  387.             if (! $this->typeClass->isIdentifierComposite && $this->typeClass->isIdentifier($this->association['indexBy'])) {
  388.                 return $this->em->find($this->typeClass->name$key);
  389.             }
  390.             return $this->em->getUnitOfWork()->getCollectionPersister($this->association)->get($this$key);
  391.         }
  392.         return parent::get($key);
  393.     }
  394.     public function count(): int
  395.     {
  396.         if (! $this->initialized && $this->association !== null && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) {
  397.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  398.             return $persister->count($this) + ($this->isDirty $this->collection->count() : 0);
  399.         }
  400.         return parent::count();
  401.     }
  402.     /**
  403.      * {@inheritdoc}
  404.      */
  405.     public function set($key$value): void
  406.     {
  407.         parent::set($key$value);
  408.         $this->changed();
  409.         if (is_object($value) && $this->em) {
  410.             $this->em->getUnitOfWork()->cancelOrphanRemoval($value);
  411.         }
  412.     }
  413.     /**
  414.      * {@inheritdoc}
  415.      */
  416.     public function add($value): bool
  417.     {
  418.         $this->collection->add($value);
  419.         $this->changed();
  420.         if (is_object($value) && $this->em) {
  421.             $this->em->getUnitOfWork()->cancelOrphanRemoval($value);
  422.         }
  423.         return true;
  424.     }
  425.     /* ArrayAccess implementation */
  426.     /**
  427.      * {@inheritdoc}
  428.      */
  429.     public function offsetExists($offset): bool
  430.     {
  431.         return $this->containsKey($offset);
  432.     }
  433.     /**
  434.      * {@inheritdoc}
  435.      */
  436.     public function offsetGet($offset)
  437.     {
  438.         return $this->get($offset);
  439.     }
  440.     /**
  441.      * {@inheritdoc}
  442.      */
  443.     public function offsetSet($offset$value): void
  444.     {
  445.         if (! isset($offset)) {
  446.             $this->add($value);
  447.             return;
  448.         }
  449.         $this->set($offset$value);
  450.     }
  451.     /**
  452.      * {@inheritdoc}
  453.      *
  454.      * @return object|null
  455.      */
  456.     public function offsetUnset($offset)
  457.     {
  458.         return $this->remove($offset);
  459.     }
  460.     public function isEmpty(): bool
  461.     {
  462.         return $this->collection->isEmpty() && $this->count() === 0;
  463.     }
  464.     public function clear(): void
  465.     {
  466.         if ($this->initialized && $this->isEmpty()) {
  467.             $this->collection->clear();
  468.             return;
  469.         }
  470.         $uow $this->em->getUnitOfWork();
  471.         if (
  472.             $this->association['type'] & ClassMetadata::TO_MANY &&
  473.             $this->association['orphanRemoval'] &&
  474.             $this->owner
  475.         ) {
  476.             // we need to initialize here, as orphan removal acts like implicit cascadeRemove,
  477.             // hence for event listeners we need the objects in memory.
  478.             $this->initialize();
  479.             foreach ($this->collection as $element) {
  480.                 $uow->scheduleOrphanRemoval($element);
  481.             }
  482.         }
  483.         $this->collection->clear();
  484.         $this->initialized true// direct call, {@link initialize()} is too expensive
  485.         if ($this->association['isOwningSide'] && $this->owner) {
  486.             $this->changed();
  487.             $uow->scheduleCollectionDeletion($this);
  488.             $this->takeSnapshot();
  489.         }
  490.     }
  491.     /**
  492.      * Called by PHP when this collection is serialized. Ensures that only the
  493.      * elements are properly serialized.
  494.      *
  495.      * Internal note: Tried to implement Serializable first but that did not work well
  496.      *                with circular references. This solution seems simpler and works well.
  497.      *
  498.      * @return string[]
  499.      * @psalm-return array{0: string, 1: string}
  500.      */
  501.     public function __sleep(): array
  502.     {
  503.         return ['collection''initialized'];
  504.     }
  505.     /**
  506.      * Extracts a slice of $length elements starting at position $offset from the Collection.
  507.      *
  508.      * If $length is null it returns all elements from $offset to the end of the Collection.
  509.      * Keys have to be preserved by this method. Calling this method will only return the
  510.      * selected slice and NOT change the elements contained in the collection slice is called on.
  511.      *
  512.      * @param int      $offset
  513.      * @param int|null $length
  514.      *
  515.      * @psalm-return array<TKey,T>
  516.      */
  517.     public function slice($offset$length null): array
  518.     {
  519.         if (! $this->initialized && ! $this->isDirty && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) {
  520.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  521.             return $persister->slice($this$offset$length);
  522.         }
  523.         return parent::slice($offset$length);
  524.     }
  525.     /**
  526.      * Cleans up internal state of cloned persistent collection.
  527.      *
  528.      * The following problems have to be prevented:
  529.      * 1. Added entities are added to old PC
  530.      * 2. New collection is not dirty, if reused on other entity nothing
  531.      * changes.
  532.      * 3. Snapshot leads to invalid diffs being generated.
  533.      * 4. Lazy loading grabs entities from old owner object.
  534.      * 5. New collection is connected to old owner and leads to duplicate keys.
  535.      */
  536.     public function __clone()
  537.     {
  538.         if (is_object($this->collection)) {
  539.             $this->collection = clone $this->collection;
  540.         }
  541.         $this->initialize();
  542.         $this->owner    null;
  543.         $this->snapshot = [];
  544.         $this->changed();
  545.     }
  546.     /**
  547.      * Selects all elements from a selectable that match the expression and
  548.      * return a new collection containing these elements.
  549.      *
  550.      * @return Collection<TKey, T>
  551.      *
  552.      * @throws RuntimeException
  553.      */
  554.     public function matching(Criteria $criteria): Collection
  555.     {
  556.         if ($this->isDirty) {
  557.             $this->initialize();
  558.         }
  559.         if ($this->initialized) {
  560.             return $this->collection->matching($criteria);
  561.         }
  562.         if ($this->association['type'] === ClassMetadata::MANY_TO_MANY) {
  563.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  564.             return new ArrayCollection($persister->loadCriteria($this$criteria));
  565.         }
  566.         $builder         Criteria::expr();
  567.         $ownerExpression $builder->eq($this->backRefFieldName$this->owner);
  568.         $expression      $criteria->getWhereExpression();
  569.         $expression      $expression $builder->andX($expression$ownerExpression) : $ownerExpression;
  570.         $criteria = clone $criteria;
  571.         $criteria->where($expression);
  572.         $criteria->orderBy($criteria->getOrderings() ?: $this->association['orderBy'] ?? []);
  573.         $persister $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']);
  574.         return $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY
  575.             ? new LazyCriteriaCollection($persister$criteria)
  576.             : new ArrayCollection($persister->loadCriteria($criteria));
  577.     }
  578.     /**
  579.      * Retrieves the wrapped Collection instance.
  580.      *
  581.      * @return Collection<TKey, T>
  582.      */
  583.     public function unwrap(): Collection
  584.     {
  585.         return $this->collection;
  586.     }
  587.     protected function doInitialize(): void
  588.     {
  589.         // Has NEW objects added through add(). Remember them.
  590.         $newlyAddedDirtyObjects = [];
  591.         if ($this->isDirty) {
  592.             $newlyAddedDirtyObjects $this->collection->toArray();
  593.         }
  594.         $this->collection->clear();
  595.         $this->em->getUnitOfWork()->loadCollection($this);
  596.         $this->takeSnapshot();
  597.         if ($newlyAddedDirtyObjects) {
  598.             $this->restoreNewObjectsInDirtyCollection($newlyAddedDirtyObjects);
  599.         }
  600.     }
  601.     /**
  602.      * @param object[] $newObjects
  603.      *
  604.      * Note: the only reason why this entire looping/complexity is performed via `spl_object_hash`
  605.      *       is because we want to prevent using `array_udiff()`, which is likely to cause very
  606.      *       high overhead (complexity of O(n^2)). `array_diff_key()` performs the operation in
  607.      *       core, which is faster than using a callback for comparisons
  608.      */
  609.     private function restoreNewObjectsInDirtyCollection(array $newObjects): void
  610.     {
  611.         $loadedObjects               $this->collection->toArray();
  612.         $newObjectsByOid             array_combine(array_map('spl_object_hash'$newObjects), $newObjects);
  613.         $loadedObjectsByOid          array_combine(array_map('spl_object_hash'$loadedObjects), $loadedObjects);
  614.         $newObjectsThatWereNotLoaded array_diff_key($newObjectsByOid$loadedObjectsByOid);
  615.         if ($newObjectsThatWereNotLoaded) {
  616.             // Reattach NEW objects added through add(), if any.
  617.             array_walk($newObjectsThatWereNotLoaded, [$this->collection'add']);
  618.             $this->isDirty true;
  619.         }
  620.     }
  621. }