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

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