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

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