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.     public function contains($element): bool
  348.     {
  349.         if (! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) {
  350.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  351.             return $this->unwrap()->contains($element) || $persister->contains($this$element);
  352.         }
  353.         return parent::contains($element);
  354.     }
  355.     /**
  356.      * {@inheritdoc}
  357.      */
  358.     public function get($key)
  359.     {
  360.         if (
  361.             ! $this->initialized
  362.             && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY
  363.             && isset($this->association['indexBy'])
  364.         ) {
  365.             if (! $this->typeClass->isIdentifierComposite && $this->typeClass->isIdentifier($this->association['indexBy'])) {
  366.                 return $this->em->find($this->typeClass->name$key);
  367.             }
  368.             return $this->em->getUnitOfWork()->getCollectionPersister($this->association)->get($this$key);
  369.         }
  370.         return parent::get($key);
  371.     }
  372.     public function count(): int
  373.     {
  374.         if (! $this->initialized && $this->association !== null && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) {
  375.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  376.             return $persister->count($this) + ($this->isDirty $this->unwrap()->count() : 0);
  377.         }
  378.         return parent::count();
  379.     }
  380.     /**
  381.      * {@inheritdoc}
  382.      */
  383.     public function set($key$value): void
  384.     {
  385.         parent::set($key$value);
  386.         $this->changed();
  387.         if (is_object($value) && $this->em) {
  388.             $this->em->getUnitOfWork()->cancelOrphanRemoval($value);
  389.         }
  390.     }
  391.     /**
  392.      * {@inheritdoc}
  393.      */
  394.     public function add($value): bool
  395.     {
  396.         $this->unwrap()->add($value);
  397.         $this->changed();
  398.         if (is_object($value) && $this->em) {
  399.             $this->em->getUnitOfWork()->cancelOrphanRemoval($value);
  400.         }
  401.         return true;
  402.     }
  403.     /* ArrayAccess implementation */
  404.     /**
  405.      * {@inheritdoc}
  406.      */
  407.     public function offsetExists($offset): bool
  408.     {
  409.         return $this->containsKey($offset);
  410.     }
  411.     /**
  412.      * {@inheritdoc}
  413.      */
  414.     #[ReturnTypeWillChange]
  415.     public function offsetGet($offset)
  416.     {
  417.         return $this->get($offset);
  418.     }
  419.     /**
  420.      * {@inheritdoc}
  421.      */
  422.     public function offsetSet($offset$value): void
  423.     {
  424.         if (! isset($offset)) {
  425.             $this->add($value);
  426.             return;
  427.         }
  428.         $this->set($offset$value);
  429.     }
  430.     /**
  431.      * {@inheritdoc}
  432.      *
  433.      * @return object|null
  434.      */
  435.     #[ReturnTypeWillChange]
  436.     public function offsetUnset($offset)
  437.     {
  438.         return $this->remove($offset);
  439.     }
  440.     public function isEmpty(): bool
  441.     {
  442.         return $this->unwrap()->isEmpty() && $this->count() === 0;
  443.     }
  444.     public function clear(): void
  445.     {
  446.         if ($this->initialized && $this->isEmpty()) {
  447.             $this->unwrap()->clear();
  448.             return;
  449.         }
  450.         $uow $this->em->getUnitOfWork();
  451.         if (
  452.             $this->association['type'] & ClassMetadata::TO_MANY &&
  453.             $this->association['orphanRemoval'] &&
  454.             $this->owner
  455.         ) {
  456.             // we need to initialize here, as orphan removal acts like implicit cascadeRemove,
  457.             // hence for event listeners we need the objects in memory.
  458.             $this->initialize();
  459.             foreach ($this->unwrap() as $element) {
  460.                 $uow->scheduleOrphanRemoval($element);
  461.             }
  462.         }
  463.         $this->unwrap()->clear();
  464.         $this->initialized true// direct call, {@link initialize()} is too expensive
  465.         if ($this->association['isOwningSide'] && $this->owner) {
  466.             $this->changed();
  467.             $uow->scheduleCollectionDeletion($this);
  468.             $this->takeSnapshot();
  469.         }
  470.     }
  471.     /**
  472.      * Called by PHP when this collection is serialized. Ensures that only the
  473.      * elements are properly serialized.
  474.      *
  475.      * Internal note: Tried to implement Serializable first but that did not work well
  476.      *                with circular references. This solution seems simpler and works well.
  477.      *
  478.      * @return string[]
  479.      * @psalm-return array{0: string, 1: string}
  480.      */
  481.     public function __sleep(): array
  482.     {
  483.         return ['collection''initialized'];
  484.     }
  485.     /**
  486.      * Extracts a slice of $length elements starting at position $offset from the Collection.
  487.      *
  488.      * If $length is null it returns all elements from $offset to the end of the Collection.
  489.      * Keys have to be preserved by this method. Calling this method will only return the
  490.      * selected slice and NOT change the elements contained in the collection slice is called on.
  491.      *
  492.      * @param int      $offset
  493.      * @param int|null $length
  494.      *
  495.      * @return mixed[]
  496.      * @psalm-return array<TKey,T>
  497.      */
  498.     public function slice($offset$length null): array
  499.     {
  500.         if (! $this->initialized && ! $this->isDirty && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) {
  501.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  502.             return $persister->slice($this$offset$length);
  503.         }
  504.         return parent::slice($offset$length);
  505.     }
  506.     /**
  507.      * Cleans up internal state of cloned persistent collection.
  508.      *
  509.      * The following problems have to be prevented:
  510.      * 1. Added entities are added to old PC
  511.      * 2. New collection is not dirty, if reused on other entity nothing
  512.      * changes.
  513.      * 3. Snapshot leads to invalid diffs being generated.
  514.      * 4. Lazy loading grabs entities from old owner object.
  515.      * 5. New collection is connected to old owner and leads to duplicate keys.
  516.      */
  517.     public function __clone()
  518.     {
  519.         if (is_object($this->collection)) {
  520.             $this->collection = clone $this->collection;
  521.         }
  522.         $this->initialize();
  523.         $this->owner    null;
  524.         $this->snapshot = [];
  525.         $this->changed();
  526.     }
  527.     /**
  528.      * Selects all elements from a selectable that match the expression and
  529.      * return a new collection containing these elements.
  530.      *
  531.      * @psalm-return Collection<TKey, T>
  532.      *
  533.      * @throws RuntimeException
  534.      */
  535.     public function matching(Criteria $criteria): Collection
  536.     {
  537.         if ($this->isDirty) {
  538.             $this->initialize();
  539.         }
  540.         if ($this->initialized) {
  541.             return $this->unwrap()->matching($criteria);
  542.         }
  543.         if ($this->association['type'] === ClassMetadata::MANY_TO_MANY) {
  544.             $persister $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  545.             return new ArrayCollection($persister->loadCriteria($this$criteria));
  546.         }
  547.         $builder         Criteria::expr();
  548.         $ownerExpression $builder->eq($this->backRefFieldName$this->owner);
  549.         $expression      $criteria->getWhereExpression();
  550.         $expression      $expression $builder->andX($expression$ownerExpression) : $ownerExpression;
  551.         $criteria = clone $criteria;
  552.         $criteria->where($expression);
  553.         $criteria->orderBy($criteria->getOrderings() ?: $this->association['orderBy'] ?? []);
  554.         $persister $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']);
  555.         return $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY
  556.             ? new LazyCriteriaCollection($persister$criteria)
  557.             : new ArrayCollection($persister->loadCriteria($criteria));
  558.     }
  559.     /**
  560.      * Retrieves the wrapped Collection instance.
  561.      *
  562.      * @return Collection<TKey, T>
  563.      */
  564.     public function unwrap(): Collection
  565.     {
  566.         assert($this->collection !== null);
  567.         return $this->collection;
  568.     }
  569.     protected function doInitialize(): void
  570.     {
  571.         // Has NEW objects added through add(). Remember them.
  572.         $newlyAddedDirtyObjects = [];
  573.         if ($this->isDirty) {
  574.             $newlyAddedDirtyObjects $this->unwrap()->toArray();
  575.         }
  576.         $this->unwrap()->clear();
  577.         $this->em->getUnitOfWork()->loadCollection($this);
  578.         $this->takeSnapshot();
  579.         if ($newlyAddedDirtyObjects) {
  580.             $this->restoreNewObjectsInDirtyCollection($newlyAddedDirtyObjects);
  581.         }
  582.     }
  583.     /**
  584.      * @param object[] $newObjects
  585.      *
  586.      * Note: the only reason why this entire looping/complexity is performed via `spl_object_id`
  587.      *       is because we want to prevent using `array_udiff()`, which is likely to cause very
  588.      *       high overhead (complexity of O(n^2)). `array_diff_key()` performs the operation in
  589.      *       core, which is faster than using a callback for comparisons
  590.      */
  591.     private function restoreNewObjectsInDirtyCollection(array $newObjects): void
  592.     {
  593.         $loadedObjects               $this->unwrap()->toArray();
  594.         $newObjectsByOid             array_combine(array_map('spl_object_id'$newObjects), $newObjects);
  595.         $loadedObjectsByOid          array_combine(array_map('spl_object_id'$loadedObjects), $loadedObjects);
  596.         $newObjectsThatWereNotLoaded array_diff_key($newObjectsByOid$loadedObjectsByOid);
  597.         if ($newObjectsThatWereNotLoaded) {
  598.             // Reattach NEW objects added through add(), if any.
  599.             array_walk($newObjectsThatWereNotLoaded, [$this->unwrap(), 'add']);
  600.             $this->isDirty true;
  601.         }
  602.     }
  603. }