PersistentCollection.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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 \Doctrine\ORM\Mapping\AssociationMapping
  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->association['orphanRemoval']) {
  345. $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed);
  346. }
  347. return $removed;
  348. }
  349. /**
  350. * {@inheritdoc}
  351. */
  352. public function removeElement($element)
  353. {
  354. if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  355. if ($this->coll->contains($element)) {
  356. return $this->coll->removeElement($element);
  357. }
  358. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  359. if ($persister->removeElement($this, $element)) {
  360. return $element;
  361. }
  362. return null;
  363. }
  364. $this->initialize();
  365. $removed = $this->coll->removeElement($element);
  366. if ( ! $removed) {
  367. return $removed;
  368. }
  369. $this->changed();
  370. if ($this->association !== null &&
  371. $this->association['type'] & ClassMetadata::TO_MANY &&
  372. $this->association['orphanRemoval']) {
  373. $this->em->getUnitOfWork()->scheduleOrphanRemoval($element);
  374. }
  375. return $removed;
  376. }
  377. /**
  378. * {@inheritdoc}
  379. */
  380. public function containsKey($key)
  381. {
  382. $this->initialize();
  383. return $this->coll->containsKey($key);
  384. }
  385. /**
  386. * {@inheritdoc}
  387. */
  388. public function contains($element)
  389. {
  390. if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  391. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  392. return $this->coll->contains($element) || $persister->contains($this, $element);
  393. }
  394. $this->initialize();
  395. return $this->coll->contains($element);
  396. }
  397. /**
  398. * {@inheritdoc}
  399. */
  400. public function exists(Closure $p)
  401. {
  402. $this->initialize();
  403. return $this->coll->exists($p);
  404. }
  405. /**
  406. * {@inheritdoc}
  407. */
  408. public function indexOf($element)
  409. {
  410. $this->initialize();
  411. return $this->coll->indexOf($element);
  412. }
  413. /**
  414. * {@inheritdoc}
  415. */
  416. public function get($key)
  417. {
  418. $this->initialize();
  419. return $this->coll->get($key);
  420. }
  421. /**
  422. * {@inheritdoc}
  423. */
  424. public function getKeys()
  425. {
  426. $this->initialize();
  427. return $this->coll->getKeys();
  428. }
  429. /**
  430. * {@inheritdoc}
  431. */
  432. public function getValues()
  433. {
  434. $this->initialize();
  435. return $this->coll->getValues();
  436. }
  437. /**
  438. * {@inheritdoc}
  439. */
  440. public function count()
  441. {
  442. if ( ! $this->initialized && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  443. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  444. return $persister->count($this) + ($this->isDirty ? $this->coll->count() : 0);
  445. }
  446. $this->initialize();
  447. return $this->coll->count();
  448. }
  449. /**
  450. * {@inheritdoc}
  451. */
  452. public function set($key, $value)
  453. {
  454. $this->initialize();
  455. $this->coll->set($key, $value);
  456. $this->changed();
  457. }
  458. /**
  459. * {@inheritdoc}
  460. */
  461. public function add($value)
  462. {
  463. $this->coll->add($value);
  464. $this->changed();
  465. return true;
  466. }
  467. /**
  468. * {@inheritdoc}
  469. */
  470. public function isEmpty()
  471. {
  472. $this->initialize();
  473. return $this->coll->isEmpty();
  474. }
  475. /**
  476. * {@inheritdoc}
  477. */
  478. public function getIterator()
  479. {
  480. $this->initialize();
  481. return $this->coll->getIterator();
  482. }
  483. /**
  484. * {@inheritdoc}
  485. */
  486. public function map(Closure $func)
  487. {
  488. $this->initialize();
  489. return $this->coll->map($func);
  490. }
  491. /**
  492. * {@inheritdoc}
  493. */
  494. public function filter(Closure $p)
  495. {
  496. $this->initialize();
  497. return $this->coll->filter($p);
  498. }
  499. /**
  500. * {@inheritdoc}
  501. */
  502. public function forAll(Closure $p)
  503. {
  504. $this->initialize();
  505. return $this->coll->forAll($p);
  506. }
  507. /**
  508. * {@inheritdoc}
  509. */
  510. public function partition(Closure $p)
  511. {
  512. $this->initialize();
  513. return $this->coll->partition($p);
  514. }
  515. /**
  516. * {@inheritdoc}
  517. */
  518. public function toArray()
  519. {
  520. $this->initialize();
  521. return $this->coll->toArray();
  522. }
  523. /**
  524. * {@inheritdoc}
  525. */
  526. public function clear()
  527. {
  528. if ($this->initialized && $this->isEmpty()) {
  529. return;
  530. }
  531. $uow = $this->em->getUnitOfWork();
  532. if ($this->association['type'] & ClassMetadata::TO_MANY && $this->association['orphanRemoval']) {
  533. // we need to initialize here, as orphan removal acts like implicit cascadeRemove,
  534. // hence for event listeners we need the objects in memory.
  535. $this->initialize();
  536. foreach ($this->coll as $element) {
  537. $uow->scheduleOrphanRemoval($element);
  538. }
  539. }
  540. $this->coll->clear();
  541. $this->initialized = true; // direct call, {@link initialize()} is too expensive
  542. if ($this->association['isOwningSide']) {
  543. $this->changed();
  544. $uow->scheduleCollectionDeletion($this);
  545. $this->takeSnapshot();
  546. }
  547. }
  548. /**
  549. * Called by PHP when this collection is serialized. Ensures that only the
  550. * elements are properly serialized.
  551. *
  552. * @internal Tried to implement Serializable first but that did not work well
  553. * with circular references. This solution seems simpler and works well.
  554. */
  555. public function __sleep()
  556. {
  557. return array('coll', 'initialized');
  558. }
  559. /* ArrayAccess implementation */
  560. /**
  561. * @see containsKey()
  562. */
  563. public function offsetExists($offset)
  564. {
  565. return $this->containsKey($offset);
  566. }
  567. /**
  568. * @see get()
  569. */
  570. public function offsetGet($offset)
  571. {
  572. return $this->get($offset);
  573. }
  574. /**
  575. * @see add()
  576. * @see set()
  577. */
  578. public function offsetSet($offset, $value)
  579. {
  580. if ( ! isset($offset)) {
  581. return $this->add($value);
  582. }
  583. return $this->set($offset, $value);
  584. }
  585. /**
  586. * @see remove()
  587. */
  588. public function offsetUnset($offset)
  589. {
  590. return $this->remove($offset);
  591. }
  592. public function key()
  593. {
  594. return $this->coll->key();
  595. }
  596. /**
  597. * Gets the element of the collection at the current iterator position.
  598. */
  599. public function current()
  600. {
  601. return $this->coll->current();
  602. }
  603. /**
  604. * Moves the internal iterator position to the next element.
  605. */
  606. public function next()
  607. {
  608. return $this->coll->next();
  609. }
  610. /**
  611. * Retrieves the wrapped Collection instance.
  612. *
  613. * @return \Doctrine\Common\Collections\Collection
  614. */
  615. public function unwrap()
  616. {
  617. return $this->coll;
  618. }
  619. /**
  620. * Extract a slice of $length elements starting at position $offset from the Collection.
  621. *
  622. * If $length is null it returns all elements from $offset to the end of the Collection.
  623. * Keys have to be preserved by this method. Calling this method will only return the
  624. * selected slice and NOT change the elements contained in the collection slice is called on.
  625. *
  626. * @param int $offset
  627. * @param int $length
  628. *
  629. * @return array
  630. */
  631. public function slice($offset, $length = null)
  632. {
  633. if ( ! $this->initialized && ! $this->isDirty && $this->association['fetch'] === Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
  634. $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association);
  635. return $persister->slice($this, $offset, $length);
  636. }
  637. $this->initialize();
  638. return $this->coll->slice($offset, $length);
  639. }
  640. /**
  641. * Cleanup internal state of cloned persistent collection.
  642. *
  643. * The following problems have to be prevented:
  644. * 1. Added entities are added to old PC
  645. * 2. New collection is not dirty, if reused on other entity nothing
  646. * changes.
  647. * 3. Snapshot leads to invalid diffs being generated.
  648. * 4. Lazy loading grabs entities from old owner object.
  649. * 5. New collection is connected to old owner and leads to duplicate keys.
  650. */
  651. public function __clone()
  652. {
  653. $this->initialize();
  654. $this->owner = null;
  655. if (is_object($this->coll)) {
  656. $this->coll = clone $this->coll;
  657. }
  658. $this->snapshot = array();
  659. $this->changed();
  660. }
  661. }