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
  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
  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> $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.         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->unwrap()->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->unwrap()->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->unwrap()->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->unwrap()->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->unwrap()->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.     public function remove($key)
  290.     {
  291.         // TODO: If the keys are persistent as well (not yet implemented)
  292.         //       and the collection is not initialized and orphanRemoval is
  293.         //       not used we can issue a straight SQL delete/update on the
  294.         //       association (table). Without initializing the collection.
  295.         $removed parent::remove($key);
  296.         if (! $removed) {
  297.             return $removed;
  298.         }
  299.         $this->changed();
  300.         if (
  301.             $this->association !== null &&
  302.             $this->association['type'] & ClassMetadata::TO_MANY &&
  303.             $this->owner &&
  304.             $this->association['orphanRemoval']
  305.         ) {
  306.             $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed);
  307.         }
  308.         return $removed;
  309.     }
  310.     /**
  311.      * {@inheritdoc}
  312.      */
  313.     public function removeElement($element): bool
  314.     {
  315.         $removed parent::removeElement($element);
  316.         if (! $removed) {
  317.             return $removed;
  318.         }
  319.         $this->changed();
  320.         if (
  321.             $this->association !== null &&
  322.             $this->association['type'] & ClassMetadata::TO_MANY &&
  323.             $this->owner &&
  324.             $this->association['orphanRemoval']
  325.         ) {
  326.             $this->em->getUnitOfWork()->scheduleOrphanRemoval($element);
  327.         }
  328.         return $removed;
  329.     }
  330.     /**
  331.      * {@inheritdoc}
  332.      */
  333.     public function containsKey($key): bool
  334.     {
  335.         if (
  336.             ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY
  337.             && isset($this->association['indexBy'])
  338.         ) {
  339.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  340.             return $this->unwrap()->containsKey($key) || $persister->containsKey($this$key);
  341.         }
  342.         return parent::containsKey($key);
  343.     }
  344.     /**
  345.      * {@inheritdoc}
  346.      *
  347.      * @template TMaybeContained
  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->unwrap()->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->unwrap()->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->unwrap()->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->unwrap()->isEmpty() && $this->count() === 0;
  445.     }
  446.     public function clear(): void
  447.     {
  448.         if ($this->initialized && $this->isEmpty()) {
  449.             $this->unwrap()->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->unwrap() as $element) {
  462.                 $uow->scheduleOrphanRemoval($element);
  463.             }
  464.         }
  465.         $this->unwrap()->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->unwrap()->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.         assert($this->collection !== null);
  569.         return $this->collection;
  570.     }
  571.     protected function doInitialize(): void
  572.     {
  573.         // Has NEW objects added through add(). Remember them.
  574.         $newlyAddedDirtyObjects = [];
  575.         if ($this->isDirty) {
  576.             $newlyAddedDirtyObjects $this->unwrap()->toArray();
  577.         }
  578.         $this->unwrap()->clear();
  579.         $this->em->getUnitOfWork()->loadCollection($this);
  580.         $this->takeSnapshot();
  581.         if ($newlyAddedDirtyObjects) {
  582.             $this->restoreNewObjectsInDirtyCollection($newlyAddedDirtyObjects);
  583.         }
  584.     }
  585.     /**
  586.      * @param object[] $newObjects
  587.      *
  588.      * Note: the only reason why this entire looping/complexity is performed via `spl_object_id`
  589.      *       is because we want to prevent using `array_udiff()`, which is likely to cause very
  590.      *       high overhead (complexity of O(n^2)). `array_diff_key()` performs the operation in
  591.      *       core, which is faster than using a callback for comparisons
  592.      */
  593.     private function restoreNewObjectsInDirtyCollection(array $newObjects): void
  594.     {
  595.         $loadedObjects               $this->unwrap()->toArray();
  596.         $newObjectsByOid             array_combine(array_map('spl_object_id'$newObjects), $newObjects);
  597.         $loadedObjectsByOid          array_combine(array_map('spl_object_id'$loadedObjects), $loadedObjects);
  598.         $newObjectsThatWereNotLoaded array_diff_key($newObjectsByOid$loadedObjectsByOid);
  599.         if ($newObjectsThatWereNotLoaded) {
  600.             // Reattach NEW objects added through add(), if any.
  601.             array_walk($newObjectsThatWereNotLoaded, [$this->unwrap(), 'add']);
  602.             $this->isDirty true;
  603.         }
  604.     }
  605. }