UnitOfWork.php 75.6 KB
Newer Older
1 2
<?php
/*
romanb's avatar
romanb committed
3
 *  $Id: UnitOfWork.php 4947 2008-09-12 13:16:05Z romanb $
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.doctrine-project.org>.
20
 */
21

22
namespace Doctrine\ORM;
23

24
use Doctrine\Common\Collections\ArrayCollection,
25
    Doctrine\Common\Collections\Collection,
26
    Doctrine\Common\DoctrineException,
romanb's avatar
romanb committed
27
    Doctrine\Common\NotifyPropertyChanged,
28
    Doctrine\Common\PropertyChangedListener,
29 30
    Doctrine\ORM\Event\LifecycleEventArgs,
    Doctrine\ORM\Proxy\Proxy;
31

32
/**
33
 * The UnitOfWork is responsible for tracking changes to objects during an
34
 * "object-level" transaction and for writing out changes to the database
35
 * in the correct order.
36 37
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
38
 * @link        www.doctrine-project.org
39
 * @since       2.0
40
 * @version     $Revision$
41
 * @author      Roman Borschel <roman@code-factory.org>
42 43
 * @internal    This class contains performance-critical code. Work with care and
 *              regularly run the ORM performance tests.
44
 */
45
class UnitOfWork implements PropertyChangedListener
46
{
47
    /**
48
     * An entity is in MANAGED state when its persistence is managed by an EntityManager.
49 50 51 52
     */
    const STATE_MANAGED = 1;

    /**
53
     * An entity is new if it has just been instantiated (i.e. using the "new" operator)
54 55 56 57 58
     * and is not (yet) managed by an EntityManager.
     */
    const STATE_NEW = 2;

    /**
59
     * A detached entity is an instance with a persistent identity that is not
60 61 62 63 64
     * (or no longer) associated with an EntityManager (and a UnitOfWork).
     */
    const STATE_DETACHED = 3;

    /**
65
     * A removed entity instance is an instance with a persistent identity,
66 67 68
     * associated with an EntityManager, whose persistent state has been
     * deleted (or is scheduled for deletion).
     */
69
    const STATE_REMOVED = 4;
70

71 72
    /**
     * The identity map that holds references to all managed entities that have
73
     * an identity. The entities are grouped by their class name.
74 75
     * Since all classes in a hierarchy must share the same identifier set,
     * we always take the root class name of the hierarchy.
76
     *
77
     * @var array
78
     */
79
    private $_identityMap = array();
80

81
    /**
82 83
     * Map of all identifiers of managed entities.
     * Keys are object ids (spl_object_hash).
84 85 86 87 88
     *
     * @var array
     */
    private $_entityIdentifiers = array();

89
    /**
90
     * Map of the original entity data of managed entities.
romanb's avatar
romanb committed
91 92
     * Keys are object ids (spl_object_hash). This is used for calculating changesets
     * at commit time.
93 94
     *
     * @var array
romanb's avatar
romanb committed
95 96 97
     * @internal Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
     *           A value will only really be copied if the value in the entity is modified
     *           by the user.
98
     */
99
    private $_originalEntityData = array();
100 101

    /**
102
     * Map of entity changes. Keys are object ids (spl_object_hash).
103
     * Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
104 105 106
     *
     * @var array
     */
107
    private $_entityChangeSets = array();
108 109

    /**
110
     * The (cached) states of any known entities.
romanb's avatar
romanb committed
111
     * Keys are object ids (spl_object_hash).
112 113 114
     *
     * @var array
     */
115
    private $_entityStates = array();
116

117 118
    /**
     * Map of entities that are scheduled for dirty checking at commit time.
119
     * This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
romanb's avatar
romanb committed
120 121 122
     * Keys are object ids (spl_object_hash).
     * 
     * @var array
123
     */
124
    private $_scheduledForDirtyCheck = array();
125

126
    /**
127
     * A list of all pending entity insertions.
128 129
     *
     * @var array
130
     */
131
    private $_entityInsertions = array();
132

133
    /**
134
     * A list of all pending entity updates.
135 136
     *
     * @var array
137
     */
138
    private $_entityUpdates = array();
139 140
    
    /**
141
     * Any pending extra updates that have been scheduled by persisters.
142 143 144
     * 
     * @var array
     */
145 146
    private $_extraUpdates = array();

147
    /**
148
     * A list of all pending entity deletions.
149 150
     *
     * @var array
151
     */
152
    private $_entityDeletions = array();
153

romanb's avatar
romanb committed
154
    /**
155
     * All pending collection deletions.
romanb's avatar
romanb committed
156 157 158
     *
     * @var array
     */
159
    private $_collectionDeletions = array();
160

romanb's avatar
romanb committed
161
    /**
162
     * All pending collection updates.
romanb's avatar
romanb committed
163 164 165
     *
     * @var array
     */
166 167 168
    private $_collectionUpdates = array();

    /**
169
     * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
170 171 172 173 174 175
     * At the end of the UnitOfWork all these collections will make new snapshots
     * of their data.
     *
     * @var array
     */
    private $_visitedCollections = array();
176

177
    /**
178
     * The EntityManager that "owns" this UnitOfWork instance.
179
     *
180
     * @var Doctrine\ORM\EntityManager
181
     */
182
    private $_em;
183

184
    /**
185 186
     * The calculator used to calculate the order in which changes to
     * entities need to be written to the database.
187
     *
188
     * @var Doctrine\ORM\Internal\CommitOrderCalculator
189
     */
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    private $_commitOrderCalculator;

    /**
     * The entity persister instances used to persist entity instances.
     *
     * @var array
     */
    private $_persisters = array();

    /**
     * The collection persister instances used to persist collections.
     *
     * @var array
     */
    private $_collectionPersisters = array();
205

206
    /**
207
     * EXPERIMENTAL:
208
     * Flag for whether or not to make use of the C extension.
209
     *
210
     * @var boolean
211 212
     */
    private $_useCExtension = false;
213 214
    
    /**
215
     * The EventManager used for dispatching events.
216 217 218 219
     * 
     * @var EventManager
     */
    private $_evm;
220 221
    
    /**
222
     * Orphaned entities that are scheduled for removal.
223 224 225 226
     * 
     * @var array
     */
    private $_orphanRemovals = array();
227

228
    /**
229
     * Initializes a new UnitOfWork instance, bound to the given EntityManager.
230
     *
231
     * @param Doctrine\ORM\EntityManager $em
232
     */
233
    public function __construct(EntityManager $em)
234 235
    {
        $this->_em = $em;
236
        $this->_evm = $em->getEventManager();
237
        $this->_commitOrderCalculator = new Internal\CommitOrderCalculator();
238
        $this->_useCExtension = $this->_em->getConfiguration()->getUseCExtension();
239
    }
240

241
    /**
242
     * Commits the UnitOfWork, executing all operations that have been postponed
243 244
     * up to this point. The state of all managed entities will be synchronized with
     * the database.
romanb's avatar
romanb committed
245 246 247 248 249 250 251 252 253
     * 
     * The operations are executed in the following order:
     * 
     * 1) All entity insertions
     * 2) All entity updates
     * 3) All collection deletions
     * 4) All collection updates
     * 5) All entity deletions
     * 
254
     */
255
    public function commit()
256
    {
257
        // Compute changes done since last commit.
258 259
        $this->computeChangeSets();

260 261 262 263 264 265
        if ( ! ($this->_entityInsertions ||
                $this->_entityDeletions ||
                $this->_entityUpdates ||
                $this->_collectionUpdates ||
                $this->_collectionDeletions ||
                $this->_orphanRemovals)) {
266 267
            return; // Nothing to do.
        }
268 269 270 271 272 273
        
        if ($this->_orphanRemovals) {
            foreach ($this->_orphanRemovals as $orphan) {
                $this->remove($orphan);
            }
        }
274 275 276
        
        // Now we need a commit order to maintain referential integrity
        $commitOrder = $this->_getCommitOrder();
277

278
        $conn = $this->_em->getConnection();
279 280 281
        
        $conn->beginTransaction();
        try {            
282 283 284 285
            if ($this->_entityInsertions) {
                foreach ($commitOrder as $class) {
                    $this->_executeInserts($class);
                }
286
            }
287 288 289 290 291
            
            if ($this->_entityUpdates) {
                foreach ($commitOrder as $class) {
                    $this->_executeUpdates($class);
                }
292
            }
293

294 295 296 297
            // Extra updates that were requested by persisters.
            if ($this->_extraUpdates) {
                $this->_executeExtraUpdates();
            }
298 299 300 301 302 303 304 305 306 307 308 309 310

            // Collection deletions (deletions of complete collections)
            foreach ($this->_collectionDeletions as $collectionToDelete) {
                $this->getCollectionPersister($collectionToDelete->getMapping())
                        ->delete($collectionToDelete);
            }
            // Collection updates (deleteRows, updateRows, insertRows)
            foreach ($this->_collectionUpdates as $collectionToUpdate) {
                $this->getCollectionPersister($collectionToUpdate->getMapping())
                        ->update($collectionToUpdate);
            }

            // Entity deletions come last and need to be in reverse commit order
311 312 313 314
            if ($this->_entityDeletions) {
                for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i) {
                    $this->_executeDeletions($commitOrder[$i]);
                }
315
            }
316

317 318
            $conn->commit();
        } catch (\Exception $e) {
319
            $conn->setRollbackOnly();
320
            $conn->rollback();
romanb's avatar
romanb committed
321
            $this->clear();
322
            throw $e;
323 324
        }

325 326
        // Take new snapshots from visited collections
        foreach ($this->_visitedCollections as $coll) {
327
            $coll->takeSnapshot();
328 329
        }

330
        // Clear up
331 332 333 334 335 336 337 338 339
        $this->_entityInsertions =
        $this->_entityUpdates =
        $this->_entityDeletions =
        $this->_extraUpdates =
        $this->_entityChangeSets =
        $this->_collectionUpdates =
        $this->_collectionDeletions =
        $this->_visitedCollections =
        $this->_orphanRemovals = array();
340
    }
romanb's avatar
romanb committed
341 342 343 344
    
    /**
     * Executes any extra updates that have been scheduled.
     */
345
    private function _executeExtraUpdates()
346 347 348 349 350 351 352 353
    {
        foreach ($this->_extraUpdates as $oid => $update) {
            list ($entity, $changeset) = $update;
            $this->_entityChangeSets[$oid] = $changeset;
            $this->getEntityPersister(get_class($entity))->update($entity);
        }
    }

354
    /**
355
     * Gets the changeset for an entity.
356 357 358
     *
     * @return array
     */
359
    public function getEntityChangeSet($entity)
360
    {
361
        $oid = spl_object_hash($entity);
362 363
        if (isset($this->_entityChangeSets[$oid])) {
            return $this->_entityChangeSets[$oid];
364 365 366 367 368
        }
        return array();
    }

    /**
369
     * Computes all the changes that have been done to entities and collections
370 371
     * since the last commit and stores these changes in the _entityChangeSet map
     * temporarily for access by the persisters, until the UoW commit is finished.
372 373 374
     *
     * @param array $entities The entities for which to compute the changesets. If this
     *          parameter is not specified, the changesets of all entities in the identity
375 376 377
     *          map are computed if automatic dirty checking is enabled (the default).
     *          If automatic dirty checking is disabled, only those changesets will be
     *          computed that have been scheduled through scheduleForDirtyCheck().
378
     */
romanb's avatar
romanb committed
379
    public function computeChangeSets()
380
    {
romanb's avatar
romanb committed
381
        // Compute changes for INSERTed entities first. This must always happen.
382
        foreach ($this->_entityInsertions as $entity) {
romanb's avatar
romanb committed
383 384 385 386 387 388 389 390 391
            $class = $this->_em->getClassMetadata(get_class($entity));
            $this->_computeEntityChanges($class, $entity);
            // Look for changes in associations of the entity
            foreach ($class->associationMappings as $assoc) {
                $val = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
                if ($val !== null) {
                    $this->_computeAssociationChanges($assoc, $val);
                }
            }
392
        }
393

romanb's avatar
romanb committed
394
        // Compute changes for other MANAGED entities. Change tracking policies take effect here.
395
        foreach ($this->_identityMap as $className => $entities) {
396
            $class = $this->_em->getClassMetadata($className);
397

398
            // Skip class if change tracking happens through notification
399 400 401
            if ($class->isChangeTrackingNotify()) {
                continue;
            }
402 403

            // If change tracking is explicit, then only compute changes on explicitly saved entities
404 405 406
            $entitiesToProcess = $class->isChangeTrackingDeferredExplicit() ?
                    $this->_scheduledForDirtyCheck[$className] : $entities;

407
            foreach ($entitiesToProcess as $entity) {
408
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION are processed here.
romanb's avatar
romanb committed
409
                $oid = spl_object_hash($entity);
410
                if ( ! isset($this->_entityInsertions[$oid]) && isset($this->_entityStates[$oid])) {
411 412
                    $this->_computeEntityChanges($class, $entity);
                    // Look for changes in associations of the entity
413
                    foreach ($class->associationMappings as $assoc) {
romanb's avatar
romanb committed
414
                        $val = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
415 416
                        if ($val !== null) {
                            $this->_computeAssociationChanges($assoc, $val);
417
                        }
418
                    }
419 420 421 422
                }
            }
        }
    }
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    /**
     * Computes the changes done to a single entity.
     *
     * Modifies/populates the following properties:
     *
     * {@link _originalEntityData}
     * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
     * then it was not fetched from the database and therefore we have no original
     * entity data yet. All of the current entity data is stored as the original entity data.
     *
     * {@link _entityChangeSets}
     * The changes detected on all properties of the entity are stored there.
     * A change is a tuple array where the first entry is the old value and the second
     * entry is the new value of the property. Changesets are used by persisters
     * to INSERT/UPDATE the persistent entity state.
     *
     * {@link _entityUpdates}
     * If the entity is already fully MANAGED (has been fetched from the database before)
     * and any changes to its properties are detected, then a reference to the entity is stored
     * there to mark it for an update.
     *
     * {@link _collectionDeletions}
     * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
     * then this collection is marked for deletion.
     *
     * @param ClassMetadata $class The class descriptor of the entity.
     * @param object $entity The entity for which to compute the changes.
     */
    private function _computeEntityChanges($class, $entity)
    {
        $oid = spl_object_hash($entity);
455

456 457 458
        if ( ! $class->isInheritanceTypeNone()) {
            $class = $this->_em->getClassMetadata(get_class($entity));
        }
459

460
        $actualData = array();
romanb's avatar
romanb committed
461
        foreach ($class->reflFields as $name => $refProp) {
462 463 464
            if ( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) {
                $actualData[$name] = $refProp->getValue($entity);
            }
465

romanb's avatar
romanb committed
466 467
            if ($class->isCollectionValuedAssociation($name) && $actualData[$name] !== null
                    && ! ($actualData[$name] instanceof PersistentCollection)) {
romanb's avatar
romanb committed
468
                // If $actualData[$name] is Collection then unwrap the array
469 470
                if ( ! $actualData[$name] instanceof ArrayCollection) {
                    $actualData[$name] = new ArrayCollection($actualData[$name]);
romanb's avatar
romanb committed
471
                }
472
                
romanb's avatar
romanb committed
473
                $assoc = $class->associationMappings[$name];
474
                
475
                // Inject PersistentCollection
476 477 478 479 480 481
                $coll = new PersistentCollection(
                    $this->_em, 
                    $this->_em->getClassMetadata($assoc->targetEntityName), 
                    $actualData[$name]
                );
                
482
                $coll->setOwner($entity, $assoc);
483
                $coll->setDirty( ! $coll->isEmpty());
484
                $class->reflFields[$name]->setValue($entity, $coll);
485 486 487
                $actualData[$name] = $coll;
            }
        }
488

489
        if ( ! isset($this->_originalEntityData[$oid])) {
490 491
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
            // These result in an INSERT.
492 493
            $this->_originalEntityData[$oid] = $actualData;
            $this->_entityChangeSets[$oid] = array_map(
494
                function($e) { return array(null, $e); }, $actualData
495 496 497 498 499 500 501 502 503 504 505 506
            );
        } else {
            // Entity is "fully" MANAGED: it was already fully persisted before
            // and we have a copy of the original data
            $originalData = $this->_originalEntityData[$oid];
            $changeSet = array();
            $entityIsDirty = false;

            foreach ($actualData as $propName => $actualValue) {
                $orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
                if (is_object($orgValue) && $orgValue !== $actualValue) {
                    $changeSet[$propName] = array($orgValue, $actualValue);
507
                } else if ($orgValue != $actualValue || ($orgValue === null ^ $actualValue === null)) {
508 509 510 511
                    $changeSet[$propName] = array($orgValue, $actualValue);
                }

                if (isset($changeSet[$propName])) {
romanb's avatar
romanb committed
512 513
                    if (isset($class->associationMappings[$propName])) {
                        $assoc = $class->associationMappings[$propName];
514 515 516 517 518 519 520
                        if ($assoc->isOneToOne()) {
                            if ($assoc->isOwningSide) {
                                $entityIsDirty = true;
                            }
                            if ($actualValue === null && $assoc->orphanRemoval) {
                                $this->scheduleOrphanRemoval($orgValue);
                            }
521 522 523 524
                        } else if ($orgValue instanceof PersistentCollection) {
                            // A PersistentCollection was de-referenced, so delete it.
                            if  ( ! in_array($orgValue, $this->_collectionDeletions, true)) {
                                $this->_collectionDeletions[] = $orgValue;
525 526
                            }
                        }
527 528
                    } else {
                        $entityIsDirty = true;
529
                    }
530 531
                }
            }
532 533 534 535 536 537 538
            if ($changeSet) {
                if ($entityIsDirty) {
                    $this->_entityUpdates[$oid] = $entity;
                }
                $this->_entityChangeSets[$oid] = $changeSet;
                $this->_originalEntityData[$oid] = $actualData;
            }
539
        }
540
    }
541

542
    /**
543
     * Computes the changes of an association.
544
     *
545 546
     * @param AssociationMapping $assoc
     * @param mixed $value The value of the association.
547
     */
548
    private function _computeAssociationChanges($assoc, $value)
549
    {
550
        if ($value instanceof PersistentCollection && $value->isDirty()) {
romanb's avatar
romanb committed
551
            if ($assoc->isOwningSide) {
552 553 554 555
                $this->_collectionUpdates[] = $value;
            }
            $this->_visitedCollections[] = $value;
        }
556

557 558
        if ( ! $assoc->isCascadePersist) {
            return; // "Persistence by reachability" only if persist cascade specified
559
        }
560
        
561 562
        // Look through the entities, and in any of their associations, for transient
        // enities, recursively. ("Persistence by reachability")
563
        if ($assoc->isOneToOne()) {
564 565
            if ($value instanceof Proxy && ! $value->__isInitialized__()) {
                return; // Ignore uninitialized proxy objects
566
            }
567
            $value = array($value);
568 569
        } else if ($value instanceof PersistentCollection) {
            $value = $value->unwrap();
570
        }
571
        
romanb's avatar
romanb committed
572
        $targetClass = $this->_em->getClassMetadata($assoc->targetEntityName);
573
        foreach ($value as $entry) {
574
            $state = $this->getEntityState($entry, self::STATE_NEW);
575 576 577
            $oid = spl_object_hash($entry);
            if ($state == self::STATE_NEW) {
                // Get identifier, if possible (not post-insert)
578
                $idGen = $targetClass->idGenerator;
579
                if ( ! $idGen->isPostInsertGenerator()) {
580
                    $idValue = $idGen->generate($this->_em, $entry);
581
                    $this->_entityStates[$oid] = self::STATE_MANAGED;
582
                    if ( ! $idGen instanceof \Doctrine\ORM\Id\Assigned) {
583 584 585 586 587 588 589 590
                        $this->_entityIdentifiers[$oid] = array($idValue);
                        $targetClass->getSingleIdReflectionProperty()->setValue($entry, $idValue);
                    } else {
                        $this->_entityIdentifiers[$oid] = $idValue;
                    }
                    $this->addToIdentityMap($entry);
                }

591 592
                // NEW entities are INSERTed within the current unit of work.
                $this->_entityInsertions[$oid] = $entry;
593 594 595 596 597 598 599 600 601 602
                
                $this->_computeEntityChanges($targetClass, $entry);
                // Look for changes in associations of the entity
                foreach ($targetClass->associationMappings as $assoc2) {
                    $val = $targetClass->reflFields[$assoc2->sourceFieldName]->getValue($entry);
                    if ($val !== null) {
                        $this->_computeAssociationChanges($assoc2, $val);
                    }
                }
                
603
            } else if ($state == self::STATE_REMOVED) {
604
                throw DoctrineException::removedEntityInCollectionDetected();
605 606 607 608 609
            }
            // MANAGED associated entities are already taken into account
            // during changeset calculation anyway, since they are in the identity map.
        }
    }
610 611
    
    /**
612
     * INTERNAL:
613 614 615
     * Computes the changeset of an individual entity, independently of the
     * computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
     * 
romanb's avatar
romanb committed
616 617 618
     * The passed entity must be a managed entity. If the entity already has a change set
     * because this method is invoked during a commit cycle then the change sets are added.
     * whereby changes detected in this method prevail.
romanb's avatar
romanb committed
619 620
     * 
     * @ignore
romanb's avatar
romanb committed
621 622 623
     * @param ClassMetadata $class The class descriptor of the entity.
     * @param object $entity The entity for which to (re)calculate the change set.
     * @throws InvalidArgumentException If the passed entity is not MANAGED.
624 625 626 627
     */
    public function computeSingleEntityChangeSet($class, $entity)
    {
        $oid = spl_object_hash($entity);
romanb's avatar
romanb committed
628 629 630 631
        
        if ( ! isset($this->_entityStates[$oid]) || $this->_entityStates[$oid] != self::STATE_MANAGED) {
            throw new \InvalidArgumentException('Entity must be managed.');
        }
romanb's avatar
romanb committed
632 633 634 635 636
        
        /* TODO: Just return if changetracking policy is NOTIFY?
        if ($class->isChangeTrackingNotify()) {
            return;
        }*/
637 638 639 640 641 642 643 644 645 646 647 648

        if ( ! $class->isInheritanceTypeNone()) {
            $class = $this->_em->getClassMetadata(get_class($entity));
        }

        $actualData = array();
        foreach ($class->reflFields as $name => $refProp) {
            if ( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) {
                $actualData[$name] = $refProp->getValue($entity);
            }
        }
        
romanb's avatar
romanb committed
649 650 651 652 653 654 655 656 657
        $originalData = $this->_originalEntityData[$oid];
        $changeSet = array();

        foreach ($actualData as $propName => $actualValue) {
            $orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
            if (is_object($orgValue) && $orgValue !== $actualValue) {
                $changeSet[$propName] = array($orgValue, $actualValue);
            } else if ($orgValue != $actualValue || ($orgValue === null ^ $actualValue === null)) {
                $changeSet[$propName] = array($orgValue, $actualValue);
658
            }
romanb's avatar
romanb committed
659 660 661 662 663
        }

        if ($changeSet) {
            if (isset($this->_entityChangeSets[$oid])) {
                $this->_entityChangeSets[$oid] = $changeSet + $this->_entityChangeSets[$oid];
664
            }
romanb's avatar
romanb committed
665
            $this->_originalEntityData[$oid] = $actualData;
666 667
        }
    }
668

romanb's avatar
romanb committed
669 670 671
    /**
     * Executes all entity insertions for entities of the specified type.
     *
672
     * @param Doctrine\ORM\Mapping\ClassMetadata $class
romanb's avatar
romanb committed
673
     */
674
    private function _executeInserts($class)
675
    {
676
        $className = $class->name;
677
        $persister = $this->getEntityPersister($className);
678
        
romanb's avatar
romanb committed
679 680
        $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postPersist]);
        $hasListeners = $this->_evm->hasListeners(Events::postPersist);
681 682 683 684
        if ($hasLifecycleCallbacks || $hasListeners) {
            $entities = array();
        }
        
685
        foreach ($this->_entityInsertions as $oid => $entity) {
686
            if (get_class($entity) === $className) {
687
                $persister->addInsert($entity);
688
                unset($this->_entityInsertions[$oid]);
689 690 691
                if ($hasLifecycleCallbacks || $hasListeners) {
                    $entities[] = $entity;
                }
692 693
            }
        }
694
        
695
        $postInsertIds = $persister->executeInserts();
696
        
697
        if ($postInsertIds) {
romanb's avatar
romanb committed
698
            // Persister returned post-insert IDs
699 700 701 702 703 704 705 706
            foreach ($postInsertIds as $id => $entity) {
                $oid = spl_object_hash($entity);
                $idField = $class->identifier[0];
                $class->reflFields[$idField]->setValue($entity, $id);
                $this->_entityIdentifiers[$oid] = array($id);
                $this->_entityStates[$oid] = self::STATE_MANAGED;
                $this->_originalEntityData[$oid][$idField] = $id;
                $this->addToIdentityMap($entity);
707 708
            }
        }
709 710 711 712
        
        if ($hasLifecycleCallbacks || $hasListeners) {
            foreach ($entities as $entity) {
                if ($hasLifecycleCallbacks) {
romanb's avatar
romanb committed
713
                    $class->invokeLifecycleCallbacks(Events::postPersist, $entity);
714 715
                }
                if ($hasListeners) {
romanb's avatar
romanb committed
716
                    $this->_evm->dispatchEvent(Events::postPersist, new LifecycleEventArgs($entity));
717 718 719
                }
            }
        }
720
    }
721

romanb's avatar
romanb committed
722 723 724
    /**
     * Executes all entity updates for entities of the specified type.
     *
725
     * @param Doctrine\ORM\Mapping\ClassMetadata $class
romanb's avatar
romanb committed
726
     */
727 728
    private function _executeUpdates($class)
    {
729
        $className = $class->name;
730
        $persister = $this->getEntityPersister($className);
731 732 733 734 735 736
        
        $hasPreUpdateLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::preUpdate]);
        $hasPreUpdateListeners = $this->_evm->hasListeners(Events::preUpdate);
        $hasPostUpdateLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postUpdate]);
        $hasPostUpdateListeners = $this->_evm->hasListeners(Events::postUpdate);
        
737
        foreach ($this->_entityUpdates as $oid => $entity) {
738
            if (get_class($entity) == $className || $entity instanceof Proxy && $entity instanceof $className) {
739 740 741 742 743 744 745 746 747 748 749 750
                if ($hasPreUpdateLifecycleCallbacks) {
                    $class->invokeLifecycleCallbacks(Events::preUpdate, $entity);
                    if ( ! $hasPreUpdateListeners) {
                        // Need to recompute entity changeset to detect changes made in the callback.
                        $this->computeSingleEntityChangeSet($class, $entity);
                    }
                }
                if ($hasPreUpdateListeners) {
                    $this->_evm->dispatchEvent(Events::preUpdate, new LifecycleEventArgs($entity));
                    // Need to recompute entity changeset to detect changes made in the listener.
                    $this->computeSingleEntityChangeSet($class, $entity);
                }
751
                
752
                $persister->update($entity);
753
                unset($this->_entityUpdates[$oid]);
754
                
755 756 757 758 759 760
                if ($hasPostUpdateLifecycleCallbacks) {
                    $class->invokeLifecycleCallbacks(Events::postUpdate, $entity);
                }
                if ($hasPostUpdateListeners) {
                    $this->_evm->dispatchEvent(Events::postUpdate, new LifecycleEventArgs($entity));
                }
761 762
            }
        }
763
    }
764

romanb's avatar
romanb committed
765 766 767
    /**
     * Executes all entity deletions for entities of the specified type.
     *
768
     * @param Doctrine\ORM\Mapping\ClassMetadata $class
romanb's avatar
romanb committed
769
     */
770 771
    private function _executeDeletions($class)
    {
772
        $className = $class->name;
773
        $persister = $this->getEntityPersister($className);
774
                
romanb's avatar
romanb committed
775 776
        $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postRemove]);
        $hasListeners = $this->_evm->hasListeners(Events::postRemove);
777
        
778
        foreach ($this->_entityDeletions as $oid => $entity) {
779
            if (get_class($entity) == $className) {
780
                $persister->delete($entity);
781 782 783 784 785 786 787 788
                unset(
                    $this->_entityDeletions[$oid],
                    $this->_entityIdentifiers[$oid],
                    $this->_originalEntityData[$oid]
                    );
                // Entity with this $oid after deletion treated as NEW, even if the $oid
                // is obtained by a new entity because the old one went out of scope.
                $this->_entityStates[$oid] = self::STATE_NEW;
789
                
790
                if ($hasLifecycleCallbacks) {
romanb's avatar
romanb committed
791
                    $class->invokeLifecycleCallbacks(Events::postRemove, $entity);
792 793
                }
                if ($hasListeners) {
romanb's avatar
romanb committed
794
                    $this->_evm->dispatchEvent(Events::postRemove, new LifecycleEventArgs($entity));
795
                }
796 797 798 799 800 801 802 803 804
            }
        }
    }

    /**
     * Gets the commit order.
     *
     * @return array
     */
romanb's avatar
romanb committed
805
    private function _getCommitOrder(array $entityChangeSet = null)
806
    {
807
        if ($entityChangeSet === null) {
808
            $entityChangeSet = array_merge(
809 810
                    $this->_entityInsertions,
                    $this->_entityUpdates,
811 812
                    $this->_entityDeletions
                    );
romanb's avatar
romanb committed
813
        }
814
        
815 816 817
        // See if there are any new classes in the changeset, that are not in the
        // commit order graph yet (dont have a node).
        $newNodes = array();
818
        foreach ($entityChangeSet as $oid => $entity) {
819
            $className = get_class($entity);         
820 821 822 823
            if ( ! $this->_commitOrderCalculator->hasClass($className)) {
                $class = $this->_em->getClassMetadata($className);
                $this->_commitOrderCalculator->addClass($class);
                $newNodes[] = $class;
824 825 826 827
            }
        }

        // Calculate dependencies for new nodes
828
        foreach ($newNodes as $class) {
829
            foreach ($class->associationMappings as $assoc) {
830
                if ($assoc->isOwningSide && $assoc->isOneToOne()) {
831
                    $targetClass = $this->_em->getClassMetadata($assoc->targetEntityName);
832 833
                    if ( ! $this->_commitOrderCalculator->hasClass($targetClass->name)) {
                        $this->_commitOrderCalculator->addClass($targetClass);
834
                    }
835
                    $this->_commitOrderCalculator->addDependency($targetClass, $class);
836 837 838 839 840 841 842
                }
            }
        }

        return $this->_commitOrderCalculator->getCommitOrder();
    }

843
    /**
romanb's avatar
romanb committed
844
     * Schedules an entity for insertion into the database.
845
     * If the entity already has an identifier, it will be added to the identity map.
846
     *
847
     * @param object $entity The entity to schedule for insertion.
848
     */
romanb's avatar
romanb committed
849
    public function scheduleForInsert($entity)
850
    {
851
        $oid = spl_object_hash($entity);
852

853
        if (isset($this->_entityUpdates[$oid])) {
854
            throw DoctrineException::dirtyObjectCannotBeRegisteredAsNew();
855
        }
856
        if (isset($this->_entityDeletions[$oid])) {
857
            throw DoctrineException::removedObjectCannotBeRegisteredAsNew();
858
        }
859
        if (isset($this->_entityInsertions[$oid])) {
860
            throw DoctrineException::objectAlreadyRegisteredAsNew();
861
        }
862

863
        $this->_entityInsertions[$oid] = $entity;
864
        
865
        if (isset($this->_entityIdentifiers[$oid])) {
866 867
            $this->addToIdentityMap($entity);
        }
868
    }
869 870

    /**
871
     * Checks whether an entity is scheduled for insertion.
872
     *
873
     * @param object $entity
874 875
     * @return boolean
     */
romanb's avatar
romanb committed
876
    public function isScheduledForInsert($entity)
877
    {
878
        return isset($this->_entityInsertions[spl_object_hash($entity)]);
879
    }
880

881
    /**
882
     * Schedules an entity for being updated.
883
     *
884
     * @param object $entity The entity to schedule for being updated.
885
     */
romanb's avatar
romanb committed
886
    public function scheduleForUpdate($entity)
887
    {
888 889
        $oid = spl_object_hash($entity);
        if ( ! isset($this->_entityIdentifiers[$oid])) {
890
            throw DoctrineException::entityWithoutIdentityCannotBeRegisteredAsDirty();
891
        }
892
        if (isset($this->_entityDeletions[$oid])) {
893
            throw DoctrineException::removedObjectCannotBeRegisteredAsDirty();
894
        }
895

896 897
        if ( ! isset($this->_entityUpdates[$oid]) && ! isset($this->_entityInsertions[$oid])) {
            $this->_entityUpdates[$oid] = $entity;
898
        }
899
    }
900 901
    
    /**
902
     * INTERNAL:
903
     * Schedules an extra update that will be executed immediately after the
904
     * regular entity updates within the currently running commit cycle.
905
     * 
romanb's avatar
romanb committed
906 907
     * Extra updates for entities are stored as (entity, changeset) tuples.
     * 
romanb's avatar
romanb committed
908
     * @ignore
romanb's avatar
romanb committed
909 910
     * @param object $entity The entity for which to schedule an extra update.
     * @param array $changeset The changeset of the entity (what to update).
911
     */
912 913
    public function scheduleExtraUpdate($entity, array $changeset)
    {
romanb's avatar
romanb committed
914 915 916 917 918 919 920
        $oid = spl_object_hash($entity);
        if (isset($this->_extraUpdates[$oid])) {
            list($ignored, $changeset2) = $this->_extraUpdates[$oid];
            $this->_extraUpdates[$oid] = array($entity, $changeset + $changeset2);
        } else {
            $this->_extraUpdates[$oid] = array($entity, $changeset);
        }
921 922
    }

923 924 925 926 927
    /**
     * Checks whether an entity is registered as dirty in the unit of work.
     * Note: Is not very useful currently as dirty entities are only registered
     * at commit time.
     *
928
     * @param object $entity
929 930
     * @return boolean
     */
romanb's avatar
romanb committed
931
    public function isScheduledForUpdate($entity)
932
    {
933
        return isset($this->_entityUpdates[spl_object_hash($entity)]);
934
    }
935 936

    /**
937
     * Registers a deleted entity.
romanb's avatar
romanb committed
938 939
     * 
     * @param object $entity
940
     */
romanb's avatar
romanb committed
941
    public function scheduleForDelete($entity)
942
    {
943
        $oid = spl_object_hash($entity);
944
        
945
        if (isset($this->_entityInsertions[$oid])) {
946 947 948
            if ($this->isInIdentityMap($entity)) {
                $this->removeFromIdentityMap($entity);
            }
949
            unset($this->_entityInsertions[$oid]);
950
            return; // entity has not been persisted yet, so nothing more to do.
951
        }
952 953 954 955 956 957
        
        if ( ! $this->isInIdentityMap($entity)) {
            return; // ignore
        }
        
        $this->removeFromIdentityMap($entity);
romanb's avatar
romanb committed
958

959 960
        if (isset($this->_entityUpdates[$oid])) {
            unset($this->_entityUpdates[$oid]);
romanb's avatar
romanb committed
961
        }
962 963
        if ( ! isset($this->_entityDeletions[$oid])) {
            $this->_entityDeletions[$oid] = $entity;
964
        }
965 966
    }

967
    /**
968 969
     * Checks whether an entity is registered as removed/deleted with the unit
     * of work.
970
     *
971
     * @param object $entity
972
     * @return boolean
973
     */
romanb's avatar
romanb committed
974
    public function isScheduledForDelete($entity)
975
    {
976
        return isset($this->_entityDeletions[spl_object_hash($entity)]);
977
    }
978

979
    /**
romanb's avatar
romanb committed
980
     * Checks whether an entity is scheduled for insertion, update or deletion.
981 982
     * 
     * @param $entity
romanb's avatar
romanb committed
983
     * @return boolean
984
     */
romanb's avatar
romanb committed
985
    public function isEntityScheduled($entity)
986
    {
987
        $oid = spl_object_hash($entity);
988 989 990
        return isset($this->_entityInsertions[$oid]) ||
                isset($this->_entityUpdates[$oid]) ||
                isset($this->_entityDeletions[$oid]);
991
    }
992

993
    /**
994
     * INTERNAL:
995
     * Registers an entity in the identity map.
996 997 998
     * Note that entities in a hierarchy are registered with the class name of
     * the root entity.
     *
romanb's avatar
romanb committed
999
     * @ignore
1000
     * @param object $entity  The entity to register.
1001 1002
     * @return boolean  TRUE if the registration was successful, FALSE if the identity of
     *                  the entity in question is already managed.
1003
     */
1004
    public function addToIdentityMap($entity)
1005
    {
1006
        $classMetadata = $this->_em->getClassMetadata(get_class($entity));
1007
        $idHash = implode(' ', $this->_entityIdentifiers[spl_object_hash($entity)]);
1008
        if ($idHash === '') {
romanb's avatar
romanb committed
1009
            throw DoctrineException::entityMustHaveIdentityToBeAddedToIdentityMap($entity);
1010
        }
1011
        $className = $classMetadata->rootEntityName;
1012
        if (isset($this->_identityMap[$className][$idHash])) {
1013 1014
            return false;
        }
1015
        $this->_identityMap[$className][$idHash] = $entity;
romanb's avatar
romanb committed
1016
        if ($entity instanceof NotifyPropertyChanged) {
1017 1018
            $entity->addPropertyChangedListener($this);
        }
1019 1020
        return true;
    }
1021

1022 1023
    /**
     * Gets the state of an entity within the current unit of work.
1024 1025 1026 1027
     * 
     * NOTE: This method sees entities that are not MANAGED or REMOVED and have a
     *       populated identifier, whether it is generated or manually assigned, as
     *       DETACHED. This can be incorrect for manually assigned identifiers.
1028
     *
1029
     * @param object $entity
1030 1031 1032
     * @param integer $assume The state to assume if the state is not yet known. This is usually
     *                        used to avoid costly state lookups, in the worst case with a database
     *                        lookup.
1033
     * @return int The entity state.
1034
     */
1035
    public function getEntityState($entity, $assume = null)
1036
    {
1037
        $oid = spl_object_hash($entity);
romanb's avatar
romanb committed
1038
        if ( ! isset($this->_entityStates[$oid])) {
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
            // State can only be NEW or DETACHED, because MANAGED/REMOVED states are immediately
            // set by the UnitOfWork directly. We treat all entities that have a populated
            // identifier as DETACHED and all others as NEW. This is not really correct for
            // manually assigned identifiers but in that case we would need to hit the database
            // and we would like to avoid that.
            if ($assume === null) {
                if ($this->_em->getClassMetadata(get_class($entity))->getIdentifierValues($entity)) {
                    $this->_entityStates[$oid] = self::STATE_DETACHED;
                } else {
                    $this->_entityStates[$oid] = self::STATE_NEW;
                }
romanb's avatar
romanb committed
1050
            } else {
1051
                $this->_entityStates[$oid] = $assume;
romanb's avatar
romanb committed
1052 1053 1054
            }
        }
        return $this->_entityStates[$oid];
1055 1056
    }

romanb's avatar
romanb committed
1057
    /**
1058
     * INTERNAL:
romanb's avatar
romanb committed
1059 1060
     * Removes an entity from the identity map. This effectively detaches the
     * entity from the persistence management of Doctrine.
romanb's avatar
romanb committed
1061
     *
romanb's avatar
romanb committed
1062
     * @ignore
1063
     * @param object $entity
1064
     * @return boolean
romanb's avatar
romanb committed
1065
     */
1066
    public function removeFromIdentityMap($entity)
1067
    {
romanb's avatar
romanb committed
1068
        $oid = spl_object_hash($entity);
1069
        $classMetadata = $this->_em->getClassMetadata(get_class($entity));
1070
        $idHash = implode(' ', $this->_entityIdentifiers[$oid]);
1071
        if ($idHash === '') {
1072
            throw DoctrineException::entityMustHaveIdentifyToBeRemovedFromIdentityMap($entity);
1073
        }
1074
        $className = $classMetadata->rootEntityName;
1075 1076
        if (isset($this->_identityMap[$className][$idHash])) {
            unset($this->_identityMap[$className][$idHash]);
romanb's avatar
romanb committed
1077
            $this->_entityStates[$oid] = self::STATE_DETACHED;
1078 1079 1080 1081 1082
            return true;
        }

        return false;
    }
1083

romanb's avatar
romanb committed
1084
    /**
1085
     * INTERNAL:
romanb's avatar
romanb committed
1086
     * Gets an entity in the identity map by its identifier hash.
romanb's avatar
romanb committed
1087
     *
romanb's avatar
romanb committed
1088
     * @ignore
1089 1090
     * @param string $idHash
     * @param string $rootClassName
1091
     * @return object
romanb's avatar
romanb committed
1092
     */
1093
    public function getByIdHash($idHash, $rootClassName)
1094
    {
1095 1096
        return $this->_identityMap[$rootClassName][$idHash];
    }
1097 1098

    /**
1099
     * INTERNAL:
1100 1101 1102
     * Tries to get an entity by its identifier hash. If no entity is found for
     * the given hash, FALSE is returned.
     *
romanb's avatar
romanb committed
1103
     * @ignore
romanb's avatar
romanb committed
1104 1105
     * @param string $idHash
     * @param string $rootClassName
1106 1107
     * @return mixed The found entity or FALSE.
     */
1108 1109
    public function tryGetByIdHash($idHash, $rootClassName)
    {
romanb's avatar
romanb committed
1110 1111
        return isset($this->_identityMap[$rootClassName][$idHash]) ?
                $this->_identityMap[$rootClassName][$idHash] : false;
1112
    }
1113

1114
    /**
1115
     * Checks whether an entity is registered in the identity map of this UnitOfWork.
1116
     *
1117
     * @param object $entity
1118 1119
     * @return boolean
     */
1120
    public function isInIdentityMap($entity)
1121
    {
1122 1123 1124 1125
        $oid = spl_object_hash($entity);
        if ( ! isset($this->_entityIdentifiers[$oid])) {
            return false;
        }
1126
        $classMetadata = $this->_em->getClassMetadata(get_class($entity));
1127
        $idHash = implode(' ', $this->_entityIdentifiers[$oid]);
1128
        if ($idHash === '') {
1129 1130
            return false;
        }
1131
        
1132
        return isset($this->_identityMap[$classMetadata->rootEntityName][$idHash]);
1133
    }
1134

romanb's avatar
romanb committed
1135
    /**
1136
     * INTERNAL:
romanb's avatar
romanb committed
1137 1138
     * Checks whether an identifier hash exists in the identity map.
     *
romanb's avatar
romanb committed
1139
     * @ignore
romanb's avatar
romanb committed
1140 1141 1142 1143
     * @param string $idHash
     * @param string $rootClassName
     * @return boolean
     */
1144
    public function containsIdHash($idHash, $rootClassName)
1145
    {
1146
        return isset($this->_identityMap[$rootClassName][$idHash]);
1147
    }
1148 1149

    /**
1150
     * Persists an entity as part of the current unit of work.
1151
     *
1152
     * @param object $entity The entity to persist.
1153
     */
romanb's avatar
romanb committed
1154
    public function persist($entity)
1155 1156
    {
        $visited = array();
romanb's avatar
romanb committed
1157
        $this->_doPersist($entity, $visited);
1158 1159 1160 1161 1162 1163
    }

    /**
     * Saves an entity as part of the current unit of work.
     * This method is internally called during save() cascades as it tracks
     * the already visited entities to prevent infinite recursions.
1164 1165
     * 
     * NOTE: This method always considers entities with a manually assigned identifier as NEW.
1166
     *
1167
     * @param object $entity The entity to persist.
romanb's avatar
romanb committed
1168
     * @param array $visited The already visited entities.
1169
     */
romanb's avatar
romanb committed
1170
    private function _doPersist($entity, array &$visited)
1171
    {
1172
        $oid = spl_object_hash($entity);
1173
        if (isset($visited[$oid])) {
1174 1175 1176
            return; // Prevent infinite recursion
        }

1177
        $visited[$oid] = $entity; // Mark visited
1178

romanb's avatar
romanb committed
1179 1180 1181
        $class = $this->_em->getClassMetadata(get_class($entity));
        $entityState = $this->getEntityState($entity, self::STATE_NEW);
        
1182
        switch ($entityState) {
1183
            case self::STATE_MANAGED:
1184
                // Nothing to do, except if policy is "deferred explicit"
1185
                if ($class->isChangeTrackingDeferredExplicit()) {
1186 1187
                    $this->scheduleForDirtyCheck($entity);
                }
1188
                break;
1189
            case self::STATE_NEW:
romanb's avatar
romanb committed
1190 1191
                if (isset($class->lifecycleCallbacks[Events::prePersist])) {
                    $class->invokeLifecycleCallbacks(Events::prePersist, $entity);
1192
                }
romanb's avatar
romanb committed
1193 1194
                if ($this->_evm->hasListeners(Events::prePersist)) {
                    $this->_evm->dispatchEvent(Events::prePersist, new LifecycleEventArgs($entity));
1195
                }
1196
                
romanb's avatar
romanb committed
1197
                $idGen = $class->idGenerator;
romanb's avatar
romanb committed
1198
                if ( ! $idGen->isPostInsertGenerator()) {
1199
                    $idValue = $idGen->generate($this->_em, $entity);
1200
                    if ( ! $idGen instanceof \Doctrine\ORM\Id\Assigned) {
1201
                        $this->_entityIdentifiers[$oid] = array($idValue);
1202
                        $class->setIdentifierValues($entity, $idValue);
1203 1204
                    } else {
                        $this->_entityIdentifiers[$oid] = $idValue;
1205
                    }
1206
                }
romanb's avatar
romanb committed
1207 1208 1209
                $this->_entityStates[$oid] = self::STATE_MANAGED;
                
                $this->scheduleForInsert($entity);
1210
                break;
1211
            case self::STATE_DETACHED:
1212
                throw DoctrineException::notImplemented("Behavior of save() for a detached entity "
1213
                        . "is not yet defined.");
1214
            case self::STATE_REMOVED:
1215
                // Entity becomes managed again
romanb's avatar
romanb committed
1216
                if ($this->isScheduledForDelete($entity)) {
1217
                    unset($this->_entityDeletions[$oid]);
1218 1219
                } else {
                    //FIXME: There's more to think of here...
romanb's avatar
romanb committed
1220
                    $this->scheduleForInsert($entity);
1221
                }
1222
                break;
1223
            default:
1224
                throw DoctrineException::invalidEntityState($entityState);
1225
        }
1226
        
romanb's avatar
romanb committed
1227
        $this->_cascadePersist($entity, $visited);
1228
    }
1229 1230 1231 1232

    /**
     * Deletes an entity as part of the current unit of work.
     *
1233
     * @param object $entity The entity to remove.
1234
     */
romanb's avatar
romanb committed
1235
    public function remove($entity)
1236
    {
1237
        $visited = array();
romanb's avatar
romanb committed
1238
        $this->_doRemove($entity, $visited);
1239
    }
1240

romanb's avatar
romanb committed
1241
    /**
1242
     * Deletes an entity as part of the current unit of work.
1243
     *
1244 1245
     * This method is internally called during delete() cascades as it tracks
     * the already visited entities to prevent infinite recursions.
romanb's avatar
romanb committed
1246
     *
1247 1248
     * @param object $entity The entity to delete.
     * @param array $visited The map of the already visited entities.
1249
     * @throws InvalidArgumentException If the instance is a detached entity.
romanb's avatar
romanb committed
1250
     */
romanb's avatar
romanb committed
1251
    private function _doRemove($entity, array &$visited)
1252
    {
1253
        $oid = spl_object_hash($entity);
1254
        if (isset($visited[$oid])) {
1255 1256 1257
            return; // Prevent infinite recursion
        }

1258
        $visited[$oid] = $entity; // mark visited
1259

1260
        $class = $this->_em->getClassMetadata(get_class($entity));
1261 1262
        $entityState = $this->getEntityState($entity);
        switch ($entityState) {
1263
            case self::STATE_NEW:
1264
            case self::STATE_REMOVED:
1265
                // nothing to do
1266
                break;
1267
            case self::STATE_MANAGED:
romanb's avatar
romanb committed
1268 1269
                if (isset($class->lifecycleCallbacks[Events::preRemove])) {
                    $class->invokeLifecycleCallbacks(Events::preRemove, $entity);
1270
                }
romanb's avatar
romanb committed
1271 1272
                if ($this->_evm->hasListeners(Events::preRemove)) {
                    $this->_evm->dispatchEvent(Events::preRemove, new LifecycleEventArgs($entity));
1273
                }
romanb's avatar
romanb committed
1274
                $this->scheduleForDelete($entity);
1275
                break;
1276
            case self::STATE_DETACHED:
1277
                throw DoctrineException::detachedEntityCannotBeRemoved();
1278
            default:
1279
                throw DoctrineException::invalidEntityState($entityState);
1280
        }
1281

romanb's avatar
romanb committed
1282
        $this->_cascadeRemove($entity, $visited);
1283 1284
    }

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    /**
     * Merges the state of the given detached entity into this UnitOfWork.
     *
     * @param object $entity
     * @return object The managed copy of the entity.
     */
    public function merge($entity)
    {
        $visited = array();
        return $this->_doMerge($entity, $visited);
    }

    /**
     * Executes a merge operation on an entity.
     *
     * @param object $entity
     * @param array $visited
     * @return object The managed copy of the entity.
1303 1304 1305
     * @throws OptimisticLockException If the entity uses optimistic locking through a version
     *         attribute and the version check against the managed copy fails.
     * @throws InvalidArgumentException If the entity instance is NEW.
1306 1307 1308 1309 1310 1311 1312
     */
    private function _doMerge($entity, array &$visited, $prevManagedCopy = null, $assoc = null)
    {
        $class = $this->_em->getClassMetadata(get_class($entity));
        $id = $class->getIdentifierValues($entity);

        if ( ! $id) {
1313 1314
            throw new \InvalidArgumentException('New entity detected during merge.'
                    . ' Persist the new entity before merging.');
1315
        }
1316
        
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
        // MANAGED entities are ignored by the merge operation
        if ($this->getEntityState($entity, self::STATE_DETACHED) == self::STATE_MANAGED) {
            $managedCopy = $entity;
        } else {
            // Try to look the entity up in the identity map.
            $managedCopy = $this->tryGetById($id, $class->rootEntityName);
            if ($managedCopy) {
                // We have the entity in-memory already, just make sure its not removed.
                if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
                    throw new \InvalidArgumentException('Removed entity detected during merge.'
                            . ' Can not merge with a removed entity.');
                }
            } else {
                // We need to fetch the managed copy in order to merge.
                $managedCopy = $this->_em->find($class->name, $id);
1332
            }
1333 1334 1335 1336
            
            if ($managedCopy === null) {
                throw new \InvalidArgumentException('New entity detected during merge.'
                        . ' Persist the new entity before merging.');
1337
            }
1338 1339 1340 1341 1342
            
            if ($class->isVersioned) {
                $managedCopyVersion = $class->reflFields[$class->versionField]->getValue($managedCopy);
                $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
                // Throw exception if versions dont match.
1343
                if ($managedCopyVersion != $entityVersion) {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
                    throw OptimisticLockException::versionMismatch();
                }
            }
    
            // Merge state of $entity into existing (managed) entity
            foreach ($class->reflFields as $name => $prop) {
                if ( ! isset($class->associationMappings[$name])) {
                    $prop->setValue($managedCopy, $prop->getValue($entity));
                } else {
                    $assoc2 = $class->associationMappings[$name];
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
                    if ($assoc2->isOneToOne()) {
                        if ( ! $assoc2->isCascadeMerge) {
                            $other = $class->reflFields[$name]->getValue($entity);
                            if ($other !== null) {
                                $targetClass = $this->_em->getClassMetadata($assoc2->targetEntityName);
                                $id = $targetClass->getIdentifierValues($other);
                                $proxy = $this->_em->getProxyFactory()->getProxy($assoc2->targetEntityName, $id);
                                $prop->setValue($managedCopy, $proxy);
                                $this->registerManaged($proxy, (array)$id, array());
                            }
                        }
1365 1366
                    } else {
                        $coll = new PersistentCollection($this->_em,
1367 1368
                                $this->_em->getClassMetadata($assoc2->targetEntityName),
                                new ArrayCollection
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
                                );
                        $coll->setOwner($managedCopy, $assoc2);
                        $coll->setInitialized($assoc2->isCascadeMerge);
                        $prop->setValue($managedCopy, $coll);
                    }
                }
                if ($class->isChangeTrackingNotify()) {
                    //TODO
                }
            }
            if ($class->isChangeTrackingDeferredExplicit()) {
1380 1381 1382 1383 1384
                //TODO
            }
        }

        if ($prevManagedCopy !== null) {
romanb's avatar
romanb committed
1385
            $assocField = $assoc->sourceFieldName;
1386 1387
            $prevClass = $this->_em->getClassMetadata(get_class($prevManagedCopy));
            if ($assoc->isOneToOne()) {
1388
                $prevClass->reflFields[$assocField]->setValue($prevManagedCopy, $managedCopy);
1389
            } else {
1390
                $prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->hydrateAdd($managedCopy);
1391 1392 1393 1394 1395 1396 1397
            }
        }

        $this->_cascadeMerge($entity, $managedCopy, $visited);

        return $managedCopy;
    }
romanb's avatar
romanb committed
1398
    
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    /**
     * Detaches an entity from the persistence management. It's persistence will
     * no longer be managed by Doctrine.
     *
     * @param object $entity The entity to detach.
     */
    public function detach($entity)
    {
        $visited = array();
        $this->_doDetach($entity, $visited);
    }
    
    /**
     * Executes a detach operation on the given entity.
     * 
     * @param object $entity
     * @param array $visited
     * @internal This method always considers entities with an assigned identifier as DETACHED.
     */
    private function _doDetach($entity, array &$visited)
    {
        $oid = spl_object_hash($entity);
        if (isset($visited[$oid])) {
            return; // Prevent infinite recursion
        }

        $visited[$oid] = $entity; // mark visited
        
        switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
            case self::STATE_MANAGED:
                $this->removeFromIdentityMap($entity);
                unset($this->_entityInsertions[$oid], $this->_entityUpdates[$oid],
                        $this->_entityDeletions[$oid], $this->_entityIdentifiers[$oid],
romanb's avatar
romanb committed
1432
                        $this->_entityStates[$oid], $this->_originalEntityData[$oid]);
1433 1434 1435 1436 1437 1438 1439 1440 1441
                break;
            case self::STATE_NEW:
            case self::STATE_DETACHED:
                return;
        }
        
        $this->_cascadeDetach($entity, $visited);
    }
    
romanb's avatar
romanb committed
1442
    /**
1443 1444
     * Refreshes the state of the given entity from the database, overwriting
     * any local, unpersisted changes.
romanb's avatar
romanb committed
1445
     * 
1446
     * @param object $entity The entity to refresh.
1447
     * @throws InvalidArgumentException If the entity is not MANAGED.
romanb's avatar
romanb committed
1448 1449 1450 1451
     */
    public function refresh($entity)
    {
        $visited = array();
1452
        $this->_doRefresh($entity, $visited);
romanb's avatar
romanb committed
1453 1454 1455 1456 1457 1458 1459
    }
    
    /**
     * Executes a refresh operation on an entity.
     * 
     * @param object $entity The entity to refresh.
     * @param array $visited The already visited entities during cascades.
1460
     * @throws InvalidArgumentException If the entity is not MANAGED.
romanb's avatar
romanb committed
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
     */
    private function _doRefresh($entity, array &$visited)
    {
        $oid = spl_object_hash($entity);
        if (isset($visited[$oid])) {
            return; // Prevent infinite recursion
        }

        $visited[$oid] = $entity; // mark visited

        $class = $this->_em->getClassMetadata(get_class($entity));
1472 1473 1474 1475 1476 1477 1478
        if ($this->getEntityState($entity) == self::STATE_MANAGED) {
            $this->getEntityPersister($class->name)->refresh(
                array_combine($class->getIdentifierColumnNames(), $this->_entityIdentifiers[$oid]),
                $entity
            );
        } else {
            throw new \InvalidArgumentException("Entity is not MANAGED.");
romanb's avatar
romanb committed
1479
        }
1480
        
romanb's avatar
romanb committed
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
        $this->_cascadeRefresh($entity, $visited);
    }
    
    /**
     * Cascades a refresh operation to associated entities.
     *
     * @param object $entity
     * @param array $visited
     */
    private function _cascadeRefresh($entity, array &$visited)
    {
        $class = $this->_em->getClassMetadata(get_class($entity));
romanb's avatar
romanb committed
1493 1494
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadeRefresh) {
romanb's avatar
romanb committed
1495 1496
                continue;
            }
romanb's avatar
romanb committed
1497
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1498
            if ($relatedEntities instanceof Collection) {
romanb's avatar
romanb committed
1499 1500 1501 1502
                if ($relatedEntities instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                }
romanb's avatar
romanb committed
1503 1504 1505 1506 1507 1508 1509 1510
                foreach ($relatedEntities as $relatedEntity) {
                    $this->_doRefresh($relatedEntity, $visited);
                }
            } else if ($relatedEntities !== null) {
                $this->_doRefresh($relatedEntities, $visited);
            }
        }
    }
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
    
    /**
     * Cascades a detach operation to associated entities.
     *
     * @param object $entity
     * @param array $visited
     */
    private function _cascadeDetach($entity, array &$visited)
    {
        $class = $this->_em->getClassMetadata(get_class($entity));
romanb's avatar
romanb committed
1521 1522
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadeDetach) {
1523 1524
                continue;
            }
romanb's avatar
romanb committed
1525
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1526
            if ($relatedEntities instanceof Collection) {
1527 1528 1529 1530
                if ($relatedEntities instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                }
1531 1532 1533 1534 1535 1536 1537 1538
                foreach ($relatedEntities as $relatedEntity) {
                    $this->_doDetach($relatedEntity, $visited);
                }
            } else if ($relatedEntities !== null) {
                $this->_doDetach($relatedEntities, $visited);
            }
        }
    }
1539 1540 1541

    /**
     * Cascades a merge operation to associated entities.
1542
     *
1543 1544 1545
     * @param object $entity
     * @param object $managedCopy
     * @param array $visited
1546 1547 1548 1549
     */
    private function _cascadeMerge($entity, $managedCopy, array &$visited)
    {
        $class = $this->_em->getClassMetadata(get_class($entity));
romanb's avatar
romanb committed
1550 1551
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadeMerge) {
1552 1553
                continue;
            }
romanb's avatar
romanb committed
1554
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1555
            if ($relatedEntities instanceof Collection) {
1556 1557 1558 1559
                if ($relatedEntities instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                }
1560
                foreach ($relatedEntities as $relatedEntity) {
romanb's avatar
romanb committed
1561
                    $this->_doMerge($relatedEntity, $visited, $managedCopy, $assoc);
1562
                }
1563
            } else if ($relatedEntities !== null) {
romanb's avatar
romanb committed
1564
                $this->_doMerge($relatedEntities, $visited, $managedCopy, $assoc);
1565 1566 1567 1568
            }
        }
    }

1569 1570 1571
    /**
     * Cascades the save operation to associated entities.
     *
1572
     * @param object $entity
1573
     * @param array $visited
1574
     * @param array $insertNow
1575
     */
romanb's avatar
romanb committed
1576
    private function _cascadePersist($entity, array &$visited)
1577
    {
1578
        $class = $this->_em->getClassMetadata(get_class($entity));
romanb's avatar
romanb committed
1579 1580
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadePersist) {
1581 1582
                continue;
            }
romanb's avatar
romanb committed
1583
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1584
            if (($relatedEntities instanceof Collection || is_array($relatedEntities))) {
1585 1586 1587 1588
                if ($relatedEntities instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                }
1589
                foreach ($relatedEntities as $relatedEntity) {
romanb's avatar
romanb committed
1590
                    $this->_doPersist($relatedEntity, $visited);
1591
                }
1592
            } else if ($relatedEntities !== null) {
romanb's avatar
romanb committed
1593
                $this->_doPersist($relatedEntities, $visited);
1594 1595 1596 1597
            }
        }
    }

romanb's avatar
romanb committed
1598 1599 1600
    /**
     * Cascades the delete operation to associated entities.
     *
1601
     * @param object $entity
1602
     * @param array $visited
romanb's avatar
romanb committed
1603
     */
romanb's avatar
romanb committed
1604
    private function _cascadeRemove($entity, array &$visited)
1605
    {
romanb's avatar
romanb committed
1606
        $class = $this->_em->getClassMetadata(get_class($entity));
romanb's avatar
romanb committed
1607 1608
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadeRemove) {
romanb's avatar
romanb committed
1609 1610
                continue;
            }
romanb's avatar
romanb committed
1611
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1612
            if ($relatedEntities instanceof Collection || is_array($relatedEntities)) {
romanb's avatar
romanb committed
1613
                // If its a PersistentCollection initialization is intended! No unwrap!
romanb's avatar
romanb committed
1614
                foreach ($relatedEntities as $relatedEntity) {
romanb's avatar
romanb committed
1615
                    $this->_doRemove($relatedEntity, $visited);
romanb's avatar
romanb committed
1616
                }
1617
            } else if ($relatedEntities !== null) {
romanb's avatar
romanb committed
1618
                $this->_doRemove($relatedEntities, $visited);
romanb's avatar
romanb committed
1619 1620
            }
        }
1621
    }
romanb's avatar
romanb committed
1622 1623 1624 1625 1626 1627

    /**
     * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
     *
     * @return Doctrine\ORM\Internal\CommitOrderCalculator
     */
1628 1629 1630 1631 1632
    public function getCommitOrderCalculator()
    {
        return $this->_commitOrderCalculator;
    }

romanb's avatar
romanb committed
1633
    /**
1634
     * Clears the UnitOfWork.
romanb's avatar
romanb committed
1635
     */
1636
    public function clear()
1637
    {
romanb's avatar
romanb committed
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
        $this->_identityMap =
        $this->_entityIdentifiers =
        $this->_originalEntityData =
        $this->_entityChangeSets =
        $this->_entityStates =
        $this->_scheduledForDirtyCheck =
        $this->_entityInsertions =
        $this->_entityUpdates =
        $this->_entityDeletions =
        $this->_collectionDeletions =
        $this->_collectionUpdates =
romanb's avatar
romanb committed
1649
        $this->_extraUpdates =
romanb's avatar
romanb committed
1650
        $this->_orphanRemovals = array();
1651 1652
        $this->_commitOrderCalculator->clear();
    }
1653 1654 1655 1656 1657 1658 1659
    
    /**
     * INTERNAL:
     * Schedules an orphaned entity for removal. The remove() operation will be
     * invoked on that entity at the beginning of the next commit of this
     * UnitOfWork.
     * 
romanb's avatar
romanb committed
1660
     * @ignore
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
     * @param object $entity
     */
    public function scheduleOrphanRemoval($entity)
    {
        $this->_orphanRemovals[spl_object_hash($entity)] = $entity;
    }
    
    /**
     * INTERNAL:
     * Schedules a complete collection for removal when this UnitOfWork commits.
     *
     * @param PersistentCollection $coll
     */
1674
    public function scheduleCollectionDeletion(PersistentCollection $coll)
romanb's avatar
romanb committed
1675 1676 1677 1678 1679
    {
        //TODO: if $coll is already scheduled for recreation ... what to do?
        // Just remove $coll from the scheduled recreations?
        $this->_collectionDeletions[] = $coll;
    }
1680

1681
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
romanb's avatar
romanb committed
1682
    {
1683
        return in_array($coll, $this->_collectionsDeletions, true);
romanb's avatar
romanb committed
1684
    }
1685

1686
    /**
1687
     * INTERNAL:
1688
     * Creates an entity. Used for reconstitution of entities during hydration.
1689
     *
romanb's avatar
romanb committed
1690
     * @ignore
1691 1692
     * @param string $className  The name of the entity class.
     * @param array $data  The data for the entity.
1693
     * @return object The created entity instance.
romanb's avatar
romanb committed
1694
     * @internal Highly performance-sensitive method.
1695
     * @todo Rename: getOrCreateEntity
1696
     */
1697
    public function createEntity($className, array $data, &$hints = array())
1698
    {
1699
        $class = $this->_em->getClassMetadata($className);
1700

1701 1702 1703
        if ($class->isIdentifierComposite) {
            $id = array();
            foreach ($class->identifier as $fieldName) {
1704 1705
                $id[] = $data[$fieldName];
            }
1706
            $idHash = implode(' ', $id);
1707
        } else {
1708
            $id = array($data[$class->identifier[0]]);
1709 1710
            $idHash = $id[0];
        }
1711 1712 1713

        if (isset($this->_identityMap[$class->rootEntityName][$idHash])) {
            $entity = $this->_identityMap[$class->rootEntityName][$idHash];
1714
            $oid = spl_object_hash($entity);
1715
            $overrideLocalValues = isset($hints[Query::HINT_REFRESH]);
1716
        } else {
1717
            //$entity = clone $class->prototype;
1718
            $entity = new $className;
1719 1720
            $oid = spl_object_hash($entity);
            $this->_entityIdentifiers[$oid] = $id;
1721
            $this->_entityStates[$oid] = self::STATE_MANAGED;
1722
            $this->_originalEntityData[$oid] = $data;
1723
            $this->_identityMap[$class->rootEntityName][$idHash] = $entity;
romanb's avatar
romanb committed
1724
            if ($entity instanceof NotifyPropertyChanged) {
1725 1726
                $entity->addPropertyChangedListener($this);
            }
1727
            $overrideLocalValues = true;
1728 1729
        }

1730
        if ($overrideLocalValues) {
1731 1732 1733 1734 1735 1736 1737
            if ($this->_useCExtension) {
                doctrine_populate_data($entity, $data);
            } else {
                foreach ($data as $field => $value) {
                    if (isset($class->reflFields[$field])) {
                        $class->reflFields[$field]->setValue($entity, $value);
                    }
1738
                }
1739
            }
1740 1741 1742 1743
            
            // Properly initialize any unfetched associations, if partial objects are not allowed.
            if ( ! isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
                foreach ($class->associationMappings as $field => $assoc) {
1744
                    // Check if the association is not among the fetch-joined associations already.
1745
                    if (isset($hints['fetched'][$class->rootEntityName][$field])) {
1746 1747 1748 1749
                        continue;
                    }
                    
                    $targetClass = $this->_em->getClassMetadata($assoc->targetEntityName);
1750

1751 1752 1753 1754 1755 1756 1757
                    if ($assoc->isOneToOne()) {
                        if ($assoc->isOwningSide) {
                            $associatedId = array();
                            foreach ($assoc->targetToSourceKeyColumns as $targetColumn => $srcColumn) {
                                $joinColumnValue = $data[$srcColumn];
                                if ($joinColumnValue !== null) {
                                    $associatedId[$targetColumn] = $joinColumnValue;
1758
                                }
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
                            }
                            if ( ! $associatedId) {
                                $class->reflFields[$field]->setValue($entity, null);
                                $this->_originalEntityData[$oid][$field] = null;
                            } else {
                                // Check identity map first
                                // FIXME: Can break easily with composite keys if join column values are in
                                //        wrong order. The correct order is the one in ClassMetadata#identifier.
                                $relatedIdHash = implode(' ', $associatedId);
                                if (isset($this->_identityMap[$targetClass->rootEntityName][$relatedIdHash])) {
                                    $newValue = $this->_identityMap[$targetClass->rootEntityName][$relatedIdHash];
1770
                                } else {
1771 1772 1773 1774 1775 1776 1777 1778
                                    if ($targetClass->subClasses) {
                                        // If it might be a subtype, it can not be lazy
                                        $newValue = $assoc->load($entity, null, $this->_em, $associatedId);
                                    } else {
                                        $newValue = $this->_em->getProxyFactory()->getProxy($assoc->targetEntityName, $associatedId);
                                        $this->_entityIdentifiers[spl_object_hash($newValue)] = $associatedId;
                                        $this->_identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
                                    }
1779
                                }
1780 1781
                                $this->_originalEntityData[$oid][$field] = $newValue;
                                $class->reflFields[$field]->setValue($entity, $newValue);
1782 1783
                            }
                        } else {
1784
                            // Inverse side can never be lazy
1785
                            $targetEntity = $assoc->load($entity, null, $this->_em);
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
                            $class->reflFields[$field]->setValue($entity, $targetEntity);
                        }
                    } else {
                        // Inject collection
                        $reflField = $class->reflFields[$field];
                        $pColl = new PersistentCollection(
                            $this->_em, $targetClass,
                            $reflField->getValue($entity) ?: new ArrayCollection
                        );
                        $pColl->setOwner($entity, $assoc);
                        $reflField->setValue($entity, $pColl);
                        if ($assoc->isLazilyFetched()) {
                            $pColl->setInitialized(false);
                        } else {
                            $assoc->load($entity, $pColl, $this->_em);
1801
                        }
1802
                        $this->_originalEntityData[$oid][$field] = $pColl;
1803 1804 1805
                    }
                }
            }
1806
        }
1807
        
1808
        //TODO: These should be invoked later, after hydration, because associations may not yet be loaded here.
1809
        if (isset($class->lifecycleCallbacks[Events::postLoad])) {
1810 1811 1812
            $class->invokeLifecycleCallbacks(Events::postLoad, $entity);
        }
        if ($this->_evm->hasListeners(Events::postLoad)) {
1813
            $this->_evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($entity));
1814
        }
1815 1816

        return $entity;
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
    }

    /**
     * Gets the identity map of the UnitOfWork.
     *
     * @return array
     */
    public function getIdentityMap()
    {
        return $this->_identityMap;
    }
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843

    /**
     * Gets the original data of an entity. The original data is the data that was
     * present at the time the entity was reconstituted from the database.
     *
     * @param object $entity
     * @return array
     */
    public function getOriginalEntityData($entity)
    {
        $oid = spl_object_hash($entity);
        if (isset($this->_originalEntityData[$oid])) {
            return $this->_originalEntityData[$oid];
        }
        return array();
    }
1844 1845 1846 1847 1848 1849 1850 1851
    
    /**
     * @ignore
     */
    public function setOriginalEntityData($entity, array $data)
    {
        $this->_originalEntityData[spl_object_hash($entity)] = $data;
    }
1852 1853 1854

    /**
     * INTERNAL:
1855
     * Sets a property value of the original data array of an entity.
1856
     *
romanb's avatar
romanb committed
1857
     * @ignore
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
     * @param string $oid
     * @param string $property
     * @param mixed $value
     */
    public function setOriginalEntityProperty($oid, $property, $value)
    {
        $this->_originalEntityData[$oid][$property] = $value;
    }

    /**
     * Gets the identifier of an entity.
1869
     * The returned value is always an array of identifier values. If the entity
1870
     * has a composite identifier then the identifier values are in the same
1871
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
1872 1873 1874 1875 1876 1877 1878 1879
     *
     * @param object $entity
     * @return array The identifier values.
     */
    public function getEntityIdentifier($entity)
    {
        return $this->_entityIdentifiers[spl_object_hash($entity)];
    }
1880 1881

    /**
1882 1883
     * Tries to find an entity with the given identifier in the identity map of
     * this UnitOfWork.
1884
     *
1885 1886 1887 1888
     * @param mixed $id The entity identifier to look for.
     * @param string $rootClassName The name of the root class of the mapped entity hierarchy.
     * @return mixed Returns the entity with the specified identifier if it exists in
     *               this UnitOfWork, FALSE otherwise.
1889 1890 1891
     */
    public function tryGetById($id, $rootClassName)
    {
1892
        $idHash = implode(' ', (array) $id);
1893 1894 1895 1896 1897
        if (isset($this->_identityMap[$rootClassName][$idHash])) {
            return $this->_identityMap[$rootClassName][$idHash];
        }
        return false;
    }
1898

1899 1900 1901 1902 1903
    /**
     * Schedules an entity for dirty-checking at commit-time.
     *
     * @param object $entity The entity to schedule for dirty-checking.
     */
1904 1905
    public function scheduleForDirtyCheck($entity)
    {
1906
        $rootClassName = $this->_em->getClassMetadata(get_class($entity))->rootEntityName;
1907 1908 1909
        $this->_scheduledForDirtyCheck[$rootClassName] = $entity;
    }

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
    /**
     * Checks whether the UnitOfWork has any pending insertions.
     *
     * @return boolean TRUE if this UnitOfWork has pending insertions, FALSE otherwise.
     */
    public function hasPendingInsertions()
    {
        return ! empty($this->_entityInsertions);
    }

1920 1921 1922
    /**
     * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
     * number of entities in the identity map.
1923 1924
     *
     * @return integer
1925 1926 1927 1928
     */
    public function size()
    {
        $count = 0;
romanb's avatar
romanb committed
1929 1930 1931
        foreach ($this->_identityMap as $entitySet) {
            $count += count($entitySet);
        }
1932 1933
        return $count;
    }
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944

    /**
     * Gets the EntityPersister for an Entity.
     *
     * @param string $entityName  The name of the Entity.
     * @return Doctrine\ORM\Persister\AbstractEntityPersister
     */
    public function getEntityPersister($entityName)
    {
        if ( ! isset($this->_persisters[$entityName])) {
            $class = $this->_em->getClassMetadata($entityName);
1945
            if ($class->isInheritanceTypeNone()) {
1946
                $persister = new Persisters\StandardEntityPersister($this->_em, $class);
1947 1948 1949
            } else if ($class->isInheritanceTypeSingleTable()) {
                $persister = new Persisters\SingleTablePersister($this->_em, $class);
            } else if ($class->isInheritanceTypeJoined()) {
1950
                $persister = new Persisters\JoinedSubclassPersister($this->_em, $class);
1951
            } else {
1952
                $persister = new Persisters\UnionSubclassPersister($this->_em, $class);
1953 1954 1955 1956 1957 1958
            }
            $this->_persisters[$entityName] = $persister;
        }
        return $this->_persisters[$entityName];
    }

1959 1960 1961 1962 1963 1964
    /**
     * Gets a collection persister for a collection-valued association.
     *
     * @param AssociationMapping $association
     * @return AbstractCollectionPersister
     */
1965 1966 1967 1968
    public function getCollectionPersister($association)
    {
        $type = get_class($association);
        if ( ! isset($this->_collectionPersisters[$type])) {
1969 1970 1971 1972
            if ($association instanceof Mapping\OneToManyMapping) {
                $persister = new Persisters\OneToManyPersister($this->_em);
            } else if ($association instanceof Mapping\ManyToManyMapping) {
                $persister = new Persisters\ManyToManyPersister($this->_em);
1973 1974 1975 1976 1977
            }
            $this->_collectionPersisters[$type] = $persister;
        }
        return $this->_collectionPersisters[$type];
    }
1978

1979 1980 1981 1982 1983 1984 1985 1986
    /**
     * INTERNAL:
     * Registers an entity as managed.
     *
     * @param object $entity The entity.
     * @param array $id The identifier values.
     * @param array $data The original entity data.
     */
romanb's avatar
romanb committed
1987
    public function registerManaged($entity, array $id, array $data)
1988 1989 1990 1991 1992 1993 1994
    {
        $oid = spl_object_hash($entity);
        $this->_entityIdentifiers[$oid] = $id;
        $this->_entityStates[$oid] = self::STATE_MANAGED;
        $this->_originalEntityData[$oid] = $data;
        $this->addToIdentityMap($entity);
    }
1995

1996 1997 1998 1999 2000 2001 2002 2003
    /**
     * INTERNAL:
     * Clears the property changeset of the entity with the given OID.
     *
     * @param string $oid The entity's OID.
     */
    public function clearEntityChangeSet($oid)
    {
romanb's avatar
romanb committed
2004
        unset($this->_entityChangeSets[$oid]);
2005
    }
2006

2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
    /* PropertyChangedListener implementation */

    /**
     * Notifies this UnitOfWork of a property change in an entity.
     *
     * @param object $entity The entity that owns the property.
     * @param string $propertyName The name of the property that changed.
     * @param mixed $oldValue The old value of the property.
     * @param mixed $newValue The new value of the property.
     */
    public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
    {
2019 2020
        $oid = spl_object_hash($entity);
        $class = $this->_em->getClassMetadata(get_class($entity));
2021

2022
        $this->_entityChangeSets[$oid][$propertyName] = array($oldValue, $newValue);
2023

2024 2025 2026
        if (isset($class->associationMappings[$propertyName])) {
            $assoc = $class->associationMappings[$propertyName];
            if ($assoc->isOneToOne() && $assoc->isOwningSide) {
2027
                $this->_entityUpdates[$oid] = $entity;
2028 2029 2030 2031 2032
            } else if ($oldValue instanceof PersistentCollection) {
                // A PersistentCollection was de-referenced, so delete it.
                if  ( ! in_array($oldValue, $this->_collectionDeletions, true)) {
                    $this->_collectionDeletions[] = $oldValue;
                }
2033
            }
2034 2035
        } else {
            $this->_entityUpdates[$oid] = $entity;
2036
        }
2037
    }
2038
}