PersistentCollection.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM;
  20. use Doctrine\ORM\Mapping\ClassMetadata;
  21. use Doctrine\Common\Collections\Collection;
  22. use Doctrine\Common\Collections\ArrayCollection;
  23. use Doctrine\Common\Collections\Selectable;
  24. use Doctrine\Common\Collections\Criteria;
  25. use Doctrine\Common\Collections\ExpressionBuilder;
  26. use Closure;
  27. /**
  28. * A PersistentCollection represents a collection of elements that have persistent state.
  29. *
  30. * Collections of entities represent only the associations (links) to those entities.
  31. * That means, if the collection is part of a many-many mapping and you remove
  32. * entities from the collection, only the links in the relation table are removed (on flush).
  33. * Similarly, if you remove entities from a collection that is part of a one-many
  34. * mapping this will only result in the nulling out of the foreign keys on flush.
  35. *
  36. * @since 2.0
  37. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  38. * @author Roman Borschel <roman@code-factory.org>
  39. * @author Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
  40. * @author Stefano Rodriguez <stefano.rodriguez@fubles.com>
  41. * @todo Design for inheritance to allow custom implementations?
  42. */
  43. final class PersistentCollection implements Collection, Selectable
  44. {
  45. /**
  46. * A snapshot of the collection at the moment it was fetched from the database.
  47. * This is used to create a diff of the collection at commit time.
  48. *
  49. * @var array
  50. */
  51. private $snapshot = array();
  52. /**
  53. * The entity that owns this collection.
  54. *
  55. * @var object
  56. */
  57. private $owner;
  58. /**
  59. * The association mapping the collection belongs to.
  60. * This is currently either a OneToManyMapping or a ManyToManyMapping.
  61. *
  62. * @var array
  63. */
  64. private $association;
  65. /**
  66. * The EntityManager that manages the persistence of the collection.
  67. *
  68. * @var \Doctrine\ORM\EntityManager
  69. */
  70. private $em;
  71. /**
  72. * The name of the field on the target entities that points to the owner
  73. * of the collection. This is only set if the association is bi-directional.
  74. *
  75. * @var string
  76. */
  77. private $backRefFieldName;
  78. /**
  79. * The class descriptor of the collection's entity type.
  80. */
  81. private $typeClass;
  82. /**
  83. * Whether the collection is dirty and needs to be synchronized with the database
  84. * when the UnitOfWork that manages its persistent state commits.
  85. *
  86. * @var boolean
  87. */
  88. private $isDirty = false;
  89. /**
  90. * Whether the collection has already been initialized.
  91. *
  92. * @var boolean
  93. */
  94. private $initialized = true;
  95. /**
  96. * The wrapped Collection instance.
  97. *
  98. * @var Collection
  99. */
  100. private $coll;
  101. /**
  102. * Creates a new persistent collection.
  103. *
  104. * @param EntityManager $em The EntityManager the collection will be associated with.
  105. * @param ClassMetadata $class The class descriptor of the entity type of this collection.
  106. * @param array The collection elements.
  107. */
  108. public function __construct(EntityManager $em, $class, $coll)
  109. {
  110. $this->coll = $coll;
  111. $this->em = $em;
  112. $this->typeClass = $class;
  113. }
  114. /**
  115. * INTERNAL:
  116. * Sets the collection's owning entity together with the AssociationMapping that
  117. * describes the association between the owner and the elements of the collection.
  118. *
  119. * @param object $entity
  120. * @param AssociationMapping $assoc
  121. */
  122. public function setOwner($entity, array $assoc)
  123. {
  124. $this->owner = $entity;
  125. $this->association = $assoc;
  126. $this->backRefFieldName = $assoc['inversedBy'] ?: $assoc['mappedBy'];
  127. }
  128. /**
  129. * INTERNAL:
  130. * Gets the collection owner.
  131. *
  132. * @return object
  133. */
  134. public function getOwner()
  135. {
  136. return $this->owner;
  137. }
  138. public function getTypeClass()
  139. {
  140. return $this->typeClass;
  141. }
  142. /**
  143. * INTERNAL:
  144. * Adds an element to a collection during hydration. This will automatically
  145. * complete bidirectional associations in the case of a one-to-many association.
  146. *
  147. * @param mixed $element The element to add.
  148. */
  149. public function hydrateAdd($element)
  150. {
  151. $this->coll->add($element);
  152. // If _backRefFieldName is set and its a one-to-many association,
  153. // we need to set the back reference.
  154. if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) {
  155. // Set back reference to owner
  156. $this->typeClass->reflFields[$this->backRefFieldName]->setValue(
  157. $element, $this->owner
  158. );
  159. $this->em->getUnitOfWork()->setOriginalEntityProperty(
  160. spl_object_hash($element), $this->backRefFieldName, $this->owner
  161. );
  162. }
  163. }
  164. /**
  165. * INTERNAL:
  166. * Sets a keyed element in the collection during hydration.
  167. *
  168. * @param mixed $key The key to set.
  169. * $param mixed $value The element to set.
  170. */
  171. public function hydrateSet($key, $element)
  172. {
  173. $this->coll->set($key, $element);
  174. // If _backRefFieldName is set, then the association is bidirectional
  175. // and we need to set the back reference.
  176. if ($this->backRefFieldName && $this->association['type'] === ClassMetadata::ONE_TO_MANY) {
  177. // Set back reference to owner
  178. $this->typeClass->reflFields[$this->backRefFieldName]->setValue(
  179. $element, $this->owner
  180. );
  181. }
  182. }
  183. /**
  184. * Initializes the collection by loading its contents from the database
  185. * if the collection is not yet initialized.
  186. */
  187. public function initialize()
  188. {
  189. if ($this->initialized || ! $this->association) {
  190. return;
  191. }
  192. // Has NEW objects added through add(). Remember them.
  193. $newObjects = array();
  194. if ($this->isDirty) {
  195. $newObjects = $this->coll->toArray();
  196. }
  197. $this->coll->clear();
  198. $this->em->getUnitOfWork()->loadCollection($this);
  199. $this->takeSnapshot();
  200. // Reattach NEW objects added through add(), if any.
  201. if ($newObjects) {
  202. foreach ($newObjects as $obj) {
  203. $this->coll->add($obj);
  204. }
  205. $this->isDirty = true;
  206. }
  207. $this->initialized = true;
  208. }
  209. /**
  210. * INTERNAL:
  211. * Tells this collection to take a snapshot of its current state.
  212. */
  213. public function takeSnapshot()
  214. {
  215. $this->snapshot = $this->coll->toArray();
  216. $this->isDirty = false;
  217. }
  218. /**
  219. * INTERNAL:
  220. * Returns the last snapshot of the elements in the collection.
  221. *
  222. * @return array The last snapshot of the elements.
  223. */
  224. public function getSnapshot()
  225. {
  226. return $this->snapshot;
  227. }
  228. /**
  229. * INTERNAL:
  230. * getDeleteDiff
  231. *
  232. * @return array
  233. */
  234. public function getDeleteDiff()
  235. {
  236. return array_udiff_assoc(
  237. $this->snapshot,
  238. $this->coll->toArray(),
  239. function($a, $b) { return $a === $b ? 0 : 1; }
  240. );
  241. }
  242. /**
  243. * INTERNAL:
  244. * getInsertDiff
  245. *
  246. * @return array
  247. */
  248. public function getInsertDiff()
  249. {
  250. return array_udiff_assoc(
  251. $this->coll->toArray(),
  252. $this->snapshot,
  253. function($a, $b) { return $a === $b ? 0 : 1; }
  254. );
  255. }
  256. /**
  257. * INTERNAL: Gets the association mapping of the collection.
  258. *
  259. * @return array
  260. */
  261. public function getMapping()
  262. {
  263. return $this->association;
  264. }
  265. /**
  266. * Marks this collection as changed/dirty.
  267. */
  268. private function changed()
  269. {
  270. if ($this->isDirty) {
  271. return;
  272. }
  273. $this->isDirty = true;
  274. if ($this->association !== null &&
  275. $this->association['isOwningSide'] &&
  276. $this->association['type'] === ClassMetadata::MANY_TO_MANY &&
  277. $this->owner &&
  278. $this->em->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify()) {
  279. $this->em->getUnitOfWork()->scheduleForDirtyCheck($this->owner);
  280. }
  281. }
  282. /**
  283. * Gets a boolean flag indicating whether this collection is dirty which means
  284. * its state needs to be synchronized with the database.
  285. *
  286. * @return boolean TRUE if the collection is dirty, FALSE otherwise.
  287. */
  288. public function isDirty()
  289. {
  290. return $this->isDirty;
  291. }
  292. /**
  293. * Sets a boolean flag, indicating whether this collection is dirty.
  294. *
  295. * @param boolean $dirty Whether the collection should be marked dirty or not.
  296. */
  297. public function setDirty($dirty)
  298. {
  299. $this->isDirty = $dirty;
  300. }
  301. /**
  302. * Sets the initialized flag of the collection, forcing it into that state.
  303. *
  304. * @param boolean $bool
  305. */
  306. public function setInitialized($bool)
  307. {
  308. $this->initialized = $bool;
  309. }
  310. /**
  311. * Checks whether this collection has been initialized.
  312. *
  313. * @return boolean
  314. */
  315. public function isInitialized()
  316. {
  317. return $this->initialized;
  318. }
  319. /** {@inheritdoc} */
  320. public function first()
  321. {
  322. $this->initialize();
  323. return $this->coll->first();
  324. }
  325. /** {@inheritdoc} */
  326. public function last()
  327. {
  328. $this->initialize();
  329. return $this->coll->last();
  330. }
  331. /**
  332. * {@inheritdoc}
  333. */
  334. public function remove($key)
  335. {
  336. // TODO: If the keys are persistent as well (not yet implemented)
  337. // and the collection is not initialized and orphanRemoval is
  338. // not used we can issue a straight SQL delete/update on the
  339. // association (table). Without initializing the collection.
  340. $this->initialize();
  341. $removed = $this->coll->remove($key);
  342. if ( ! $removed) {
  343. return $removed;
  344. }
  345. $this->changed();
  346. if ($this->association !== null &&
  347. $this->association['type'] & ClassMetadata::TO_MANY &&
  348. $this->owner &&
  349. $this->association['orphanRemoval']) {
  350. $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed);
  351. }
  352. return $removed;
  353. }
  354. /**
  355. * {@inheritdoc}
  356. */
  357. public function removeElement($element)
  358. {
  359. if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  360. if ($this->coll->contains($element)) {
  361. return $this->coll->removeElement($element);
  362. }
  363. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  364. if ($persister->removeElement($this, $element)) {
  365. return $element;
  366. }
  367. return null;
  368. }
  369. $this->initialize();
  370. $removed = $this->coll->removeElement($element);
  371. if ( ! $removed) {
  372. return $removed;
  373. }
  374. $this->changed();
  375. if ($this->association !== null &&
  376. $this->association['type'] & ClassMetadata::TO_MANY &&
  377. $this->owner &&
  378. $this->association['orphanRemoval']) {
  379. $this->em->getUnitOfWork()->scheduleOrphanRemoval($element);
  380. }
  381. return $removed;
  382. }
  383. /**
  384. * {@inheritdoc}
  385. */
  386. public function containsKey($key)
  387. {
  388. $this->initialize();
  389. return $this->coll->containsKey($key);
  390. }
  391. /**
  392. * {@inheritdoc}
  393. */
  394. public function contains($element)
  395. {
  396. if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  397. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  398. return $this->coll->contains($element) || $persister->contains($this, $element);
  399. }
  400. $this->initialize();
  401. return $this->coll->contains($element);
  402. }
  403. /**
  404. * {@inheritdoc}
  405. */
  406. public function exists(Closure $p)
  407. {
  408. $this->initialize();
  409. return $this->coll->exists($p);
  410. }
  411. /**
  412. * {@inheritdoc}
  413. */
  414. public function indexOf($element)
  415. {
  416. $this->initialize();
  417. return $this->coll->indexOf($element);
  418. }
  419. /**
  420. * {@inheritdoc}
  421. */
  422. public function get($key)
  423. {
  424. $this->initialize();
  425. return $this->coll->get($key);
  426. }
  427. /**
  428. * {@inheritdoc}
  429. */
  430. public function getKeys()
  431. {
  432. $this->initialize();
  433. return $this->coll->getKeys();
  434. }
  435. /**
  436. * {@inheritdoc}
  437. */
  438. public function getValues()
  439. {
  440. $this->initialize();
  441. return $this->coll->getValues();
  442. }
  443. /**
  444. * {@inheritdoc}
  445. */
  446. public function count()
  447. {
  448. if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  449. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  450. return $persister->count($this) + ($this->isDirty ? $this->coll->count() : 0);
  451. }
  452. $this->initialize();
  453. return $this->coll->count();
  454. }
  455. /**
  456. * {@inheritdoc}
  457. */
  458. public function set($key, $value)
  459. {
  460. $this->initialize();
  461. $this->coll->set($key, $value);
  462. $this->changed();
  463. }
  464. /**
  465. * {@inheritdoc}
  466. */
  467. public function add($value)
  468. {
  469. $this->coll->add($value);
  470. $this->changed();
  471. return true;
  472. }
  473. /**
  474. * {@inheritdoc}
  475. */
  476. public function isEmpty()
  477. {
  478. $this->initialize();
  479. return $this->coll->isEmpty();
  480. }
  481. /**
  482. * {@inheritdoc}
  483. */
  484. public function getIterator()
  485. {
  486. $this->initialize();
  487. return $this->coll->getIterator();
  488. }
  489. /**
  490. * {@inheritdoc}
  491. */
  492. public function map(Closure $func)
  493. {
  494. $this->initialize();
  495. return $this->coll->map($func);
  496. }
  497. /**
  498. * {@inheritdoc}
  499. */
  500. public function filter(Closure $p)
  501. {
  502. $this->initialize();
  503. return $this->coll->filter($p);
  504. }
  505. /**
  506. * {@inheritdoc}
  507. */
  508. public function forAll(Closure $p)
  509. {
  510. $this->initialize();
  511. return $this->coll->forAll($p);
  512. }
  513. /**
  514. * {@inheritdoc}
  515. */
  516. public function partition(Closure $p)
  517. {
  518. $this->initialize();
  519. return $this->coll->partition($p);
  520. }
  521. /**
  522. * {@inheritdoc}
  523. */
  524. public function toArray()
  525. {
  526. $this->initialize();
  527. return $this->coll->toArray();
  528. }
  529. /**
  530. * {@inheritdoc}
  531. */
  532. public function clear()
  533. {
  534. if ($this->initialized && $this->isEmpty()) {
  535. return;
  536. }
  537. $uow = $this->em->getUnitOfWork();
  538. if ($this->association['type'] & ClassMetadata::TO_MANY &&
  539. $this->association['orphanRemoval'] &&
  540. $this->owner) {
  541. // we need to initialize here, as orphan removal acts like implicit cascadeRemove,
  542. // hence for event listeners we need the objects in memory.
  543. $this->initialize();
  544. foreach ($this->coll as $element) {
  545. $uow->scheduleOrphanRemoval($element);
  546. }
  547. }
  548. $this->coll->clear();
  549. $this->initialized = true; // direct call, {@link initialize()} is too expensive
  550. if ($this->association['isOwningSide'] && $this->owner) {
  551. $this->changed();
  552. $uow->scheduleCollectionDeletion($this);
  553. $this->takeSnapshot();
  554. }
  555. }
  556. /**
  557. * Called by PHP when this collection is serialized. Ensures that only the
  558. * elements are properly serialized.
  559. *
  560. * @internal Tried to implement Serializable first but that did not work well
  561. * with circular references. This solution seems simpler and works well.
  562. */
  563. public function __sleep()
  564. {
  565. return array('coll', 'initialized');
  566. }
  567. /* ArrayAccess implementation */
  568. /**
  569. * @see containsKey()
  570. */
  571. public function offsetExists($offset)
  572. {
  573. return $this->containsKey($offset);
  574. }
  575. /**
  576. * @see get()
  577. */
  578. public function offsetGet($offset)
  579. {
  580. return $this->get($offset);
  581. }
  582. /**
  583. * @see add()
  584. * @see set()
  585. */
  586. public function offsetSet($offset, $value)
  587. {
  588. if ( ! isset($offset)) {
  589. return $this->add($value);
  590. }
  591. return $this->set($offset, $value);
  592. }
  593. /**
  594. * @see remove()
  595. */
  596. public function offsetUnset($offset)
  597. {
  598. return $this->remove($offset);
  599. }
  600. public function key()
  601. {
  602. return $this->coll->key();
  603. }
  604. /**
  605. * Gets the element of the collection at the current iterator position.
  606. */
  607. public function current()
  608. {
  609. return $this->coll->current();
  610. }
  611. /**
  612. * Moves the internal iterator position to the next element.
  613. */
  614. public function next()
  615. {
  616. return $this->coll->next();
  617. }
  618. /**
  619. * Retrieves the wrapped Collection instance.
  620. *
  621. * @return \Doctrine\Common\Collections\Collection
  622. */
  623. public function unwrap()
  624. {
  625. return $this->coll;
  626. }
  627. /**
  628. * Extract a slice of $length elements starting at position $offset from the Collection.
  629. *
  630. * If $length is null it returns all elements from $offset to the end of the Collection.
  631. * Keys have to be preserved by this method. Calling this method will only return the
  632. * selected slice and NOT change the elements contained in the collection slice is called on.
  633. *
  634. * @param int $offset
  635. * @param int $length
  636. *
  637. * @return array
  638. */
  639. public function slice($offset, $length = null)
  640. {
  641. if ( ! $this->initialized && ! $this->isDirty && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  642. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  643. return $persister->slice($this, $offset, $length);
  644. }
  645. $this->initialize();
  646. return $this->coll->slice($offset, $length);
  647. }
  648. /**
  649. * Cleanup internal state of cloned persistent collection.
  650. *
  651. * The following problems have to be prevented:
  652. * 1. Added entities are added to old PC
  653. * 2. New collection is not dirty, if reused on other entity nothing
  654. * changes.
  655. * 3. Snapshot leads to invalid diffs being generated.
  656. * 4. Lazy loading grabs entities from old owner object.
  657. * 5. New collection is connected to old owner and leads to duplicate keys.
  658. */
  659. public function __clone()
  660. {
  661. if (is_object($this->coll)) {
  662. $this->coll = clone $this->coll;
  663. }
  664. $this->initialize();
  665. $this->owner = null;
  666. $this->snapshot = array();
  667. $this->changed();
  668. }
  669. /**
  670. * Select all elements from a selectable that match the expression and
  671. * return a new collection containing these elements.
  672. *
  673. * @param \Doctrine\Common\Collections\Criteria $criteria
  674. * @return Collection
  675. */
  676. public function matching(Criteria $criteria)
  677. {
  678. if ($this->initialized) {
  679. return $this->coll->matching($criteria);
  680. }
  681. if ($this->association['type'] !== ClassMetadata::ONE_TO_MANY) {
  682. throw new \RuntimeException("Matching Criteria on PersistentCollection only works on OneToMany assocations at the moment.");
  683. }
  684. // If there are NEW objects we have to check if any of them matches the criteria
  685. $newObjects = array();
  686. if ($this->isDirty) {
  687. $newObjects = $this->coll->matching($criteria)->toArray();
  688. }
  689. $targetClass = $this->em->getClassMetadata(get_class($this->owner));
  690. $id = $targetClass->getSingleIdReflectionProperty()->getValue($this->owner);
  691. $builder = Criteria::expr();
  692. $ownerExpression = $builder->eq($this->backRefFieldName, $id);
  693. $expression = $criteria->getWhereExpression();
  694. $expression = $expression ? $builder->andX($expression, $ownerExpression) : $ownerExpression;
  695. $criteria->where($expression);
  696. $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']);
  697. return new ArrayCollection(array_merge($persister->loadCriteria($criteria), $newObjects));
  698. }
  699. }