PersistentCollection.php 18KB

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