PersistentCollection.php 19 KB

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