UnitOfWork.php 76.8 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,
romanb's avatar
romanb committed
26
    Doctrine\Common\NotifyPropertyChanged,
27
    Doctrine\Common\PropertyChangedListener,
28 29
    Doctrine\ORM\Event\LifecycleEventArgs,
    Doctrine\ORM\Proxy\Proxy;
30

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

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

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

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

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

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

87
    /**
88
     * Map of the original entity data of managed entities.
romanb's avatar
romanb committed
89 90
     * Keys are object ids (spl_object_hash). This is used for calculating changesets
     * at commit time.
91 92
     *
     * @var array
romanb's avatar
romanb committed
93 94 95
     * @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.
96
     */
97
    private $_originalEntityData = array();
98 99

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

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

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

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

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

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

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

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

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

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

182
    /**
183 184
     * The calculator used to calculate the order in which changes to
     * entities need to be written to the database.
185
     *
186
     * @var Doctrine\ORM\Internal\CommitOrderCalculator
187
     */
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    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();
203

204
    /**
205
     * EXPERIMENTAL:
206
     * Flag for whether or not to make use of the C extension.
207
     *
208
     * @var boolean
209 210
     */
    private $_useCExtension = false;
211 212
    
    /**
213
     * The EventManager used for dispatching events.
214 215 216 217
     * 
     * @var EventManager
     */
    private $_evm;
218 219
    
    /**
220
     * Orphaned entities that are scheduled for removal.
221 222 223 224
     * 
     * @var array
     */
    private $_orphanRemovals = array();
225 226
    
    //private $_readOnlyObjects = 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->_useCExtension = $this->_em->getConfiguration()->getUseCExtension();
238
    }
239

240
    /**
241
     * Commits the UnitOfWork, executing all operations that have been postponed
242 243
     * up to this point. The state of all managed entities will be synchronized with
     * the database.
romanb's avatar
romanb committed
244 245 246 247 248 249 250 251 252
     * 
     * 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
     * 
253
     */
254
    public function commit()
255
    {
256
        // Compute changes done since last commit.
257 258
        $this->computeChangeSets();

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

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

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

            // 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
310 311 312 313
            if ($this->_entityDeletions) {
                for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i) {
                    $this->_executeDeletions($commitOrder[$i]);
                }
314
            }
315

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

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

329
        // Clear up
330 331 332 333 334 335 336 337
        $this->_entityInsertions =
        $this->_entityUpdates =
        $this->_entityDeletions =
        $this->_extraUpdates =
        $this->_entityChangeSets =
        $this->_collectionUpdates =
        $this->_collectionDeletions =
        $this->_visitedCollections =
338
        $this->_scheduledForDirtyCheck =
339
        $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
     */
romanb's avatar
romanb committed
373
    public function computeChangeSets()
374
    {
romanb's avatar
romanb committed
375
        // Compute changes for INSERTed entities first. This must always happen.
376
        foreach ($this->_entityInsertions as $entity) {
romanb's avatar
romanb committed
377 378 379 380 381 382 383 384 385
            $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);
                }
            }
386
        }
387

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

392
            // Skip class if change tracking happens through notification
393
            if ($class->isChangeTrackingNotify() /* || $class->isReadOnly*/) {
394 395
                continue;
            }
396 397

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

401
            foreach ($entitiesToProcess as $entity) {
402
                // Ignore uninitialized proxy objects
403
                if (/* $entity is readOnly || */ $entity instanceof Proxy && ! $entity->__isInitialized__) {
404 405
                    continue;
                }
406
                // Only MANAGED entities that are NOT SCHEDULED FOR INSERTION are processed here.
romanb's avatar
romanb committed
407
                $oid = spl_object_hash($entity);
408
                if ( ! isset($this->_entityInsertions[$oid]) && isset($this->_entityStates[$oid])) {
409 410
                    $this->_computeEntityChanges($class, $entity);
                    // Look for changes in associations of the entity
411
                    foreach ($class->associationMappings as $assoc) {
romanb's avatar
romanb committed
412
                        $val = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
413 414
                        if ($val !== null) {
                            $this->_computeAssociationChanges($assoc, $val);
415
                        }
416
                    }
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
    /**
     * 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);
453

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

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

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

487
        if ( ! isset($this->_originalEntityData[$oid])) {
488 489
            // Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
            // These result in an INSERT.
490 491
            $this->_originalEntityData[$oid] = $actualData;
            $this->_entityChangeSets[$oid] = array_map(
492
                function($e) { return array(null, $e); }, $actualData
493 494 495 496 497 498 499 500 501 502 503 504
            );
        } 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);
505
                } else if ($orgValue != $actualValue || ($orgValue === null ^ $actualValue === null)) {
506 507 508 509
                    $changeSet[$propName] = array($orgValue, $actualValue);
                }

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

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

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

596 597
                // NEW entities are INSERTed within the current unit of work.
                $this->_entityInsertions[$oid] = $entry;
598 599 600 601 602 603 604 605 606 607
                
                $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);
                    }
                }
                
608
            } else if ($state == self::STATE_REMOVED) {
609
                throw ORMException::removedEntityInCollectionDetected($entity, $assoc);
610 611 612 613 614
            }
            // MANAGED associated entities are already taken into account
            // during changeset calculation anyway, since they are in the identity map.
        }
    }
615 616
    
    /**
617
     * INTERNAL:
618 619 620
     * 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
621 622 623
     * 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
624 625
     * 
     * @ignore
romanb's avatar
romanb committed
626 627 628
     * @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.
629 630 631 632
     */
    public function computeSingleEntityChangeSet($class, $entity)
    {
        $oid = spl_object_hash($entity);
romanb's avatar
romanb committed
633 634 635 636
        
        if ( ! isset($this->_entityStates[$oid]) || $this->_entityStates[$oid] != self::STATE_MANAGED) {
            throw new \InvalidArgumentException('Entity must be managed.');
        }
romanb's avatar
romanb committed
637 638 639 640 641
        
        /* TODO: Just return if changetracking policy is NOTIFY?
        if ($class->isChangeTrackingNotify()) {
            return;
        }*/
642 643 644 645 646 647 648 649 650 651 652 653

        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
654 655 656 657 658 659 660 661 662
        $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);
663
            }
romanb's avatar
romanb committed
664 665 666 667 668
        }

        if ($changeSet) {
            if (isset($this->_entityChangeSets[$oid])) {
                $this->_entityChangeSets[$oid] = $changeSet + $this->_entityChangeSets[$oid];
669
            }
romanb's avatar
romanb committed
670
            $this->_originalEntityData[$oid] = $actualData;
671 672
        }
    }
673

romanb's avatar
romanb committed
674 675 676
    /**
     * Executes all entity insertions for entities of the specified type.
     *
677
     * @param Doctrine\ORM\Mapping\ClassMetadata $class
romanb's avatar
romanb committed
678
     */
679
    private function _executeInserts($class)
680
    {
681
        $className = $class->name;
682
        $persister = $this->getEntityPersister($className);
683
        
romanb's avatar
romanb committed
684 685
        $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postPersist]);
        $hasListeners = $this->_evm->hasListeners(Events::postPersist);
686 687 688 689
        if ($hasLifecycleCallbacks || $hasListeners) {
            $entities = array();
        }
        
690
        foreach ($this->_entityInsertions as $oid => $entity) {
691
            if (get_class($entity) === $className) {
692
                $persister->addInsert($entity);
693
                unset($this->_entityInsertions[$oid]);
694 695 696
                if ($hasLifecycleCallbacks || $hasListeners) {
                    $entities[] = $entity;
                }
697 698
            }
        }
romanb's avatar
romanb committed
699

700
        $postInsertIds = $persister->executeInserts();
701
        
702
        if ($postInsertIds) {
romanb's avatar
romanb committed
703
            // Persister returned post-insert IDs
704 705 706 707
            foreach ($postInsertIds as $id => $entity) {
                $oid = spl_object_hash($entity);
                $idField = $class->identifier[0];
                $class->reflFields[$idField]->setValue($entity, $id);
708
                $this->_entityIdentifiers[$oid] = array($idField => $id);
709 710 711
                $this->_entityStates[$oid] = self::STATE_MANAGED;
                $this->_originalEntityData[$oid][$idField] = $id;
                $this->addToIdentityMap($entity);
712 713
            }
        }
714 715 716 717
        
        if ($hasLifecycleCallbacks || $hasListeners) {
            foreach ($entities as $entity) {
                if ($hasLifecycleCallbacks) {
romanb's avatar
romanb committed
718
                    $class->invokeLifecycleCallbacks(Events::postPersist, $entity);
719 720
                }
                if ($hasListeners) {
romanb's avatar
romanb committed
721
                    $this->_evm->dispatchEvent(Events::postPersist, new LifecycleEventArgs($entity));
722 723 724
                }
            }
        }
725
    }
726

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

romanb's avatar
romanb committed
770 771 772
    /**
     * Executes all entity deletions for entities of the specified type.
     *
773
     * @param Doctrine\ORM\Mapping\ClassMetadata $class
romanb's avatar
romanb committed
774
     */
775 776
    private function _executeDeletions($class)
    {
777
        $className = $class->name;
778
        $persister = $this->getEntityPersister($className);
779
                
romanb's avatar
romanb committed
780 781
        $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postRemove]);
        $hasListeners = $this->_evm->hasListeners(Events::postRemove);
782
        
783
        foreach ($this->_entityDeletions as $oid => $entity) {
784
            if (get_class($entity) == $className || $entity instanceof Proxy && $entity instanceof $className) {
785
                $persister->delete($entity);
786 787 788 789 790 791 792 793
                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;
794
                
795
                if ($hasLifecycleCallbacks) {
romanb's avatar
romanb committed
796
                    $class->invokeLifecycleCallbacks(Events::postRemove, $entity);
797 798
                }
                if ($hasListeners) {
romanb's avatar
romanb committed
799
                    $this->_evm->dispatchEvent(Events::postRemove, new LifecycleEventArgs($entity));
800
                }
801 802 803 804 805 806 807 808 809
            }
        }
    }

    /**
     * Gets the commit order.
     *
     * @return array
     */
romanb's avatar
romanb committed
810
    private function _getCommitOrder(array $entityChangeSet = null)
811
    {
812
        if ($entityChangeSet === null) {
813
            $entityChangeSet = array_merge(
814 815
                    $this->_entityInsertions,
                    $this->_entityUpdates,
816 817
                    $this->_entityDeletions
                    );
romanb's avatar
romanb committed
818
        }
819
        
romanb's avatar
romanb committed
820 821
        $calc = $this->getCommitOrderCalculator();
        
822 823 824
        // 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();
825
        foreach ($entityChangeSet as $oid => $entity) {
826
            $className = get_class($entity);         
romanb's avatar
romanb committed
827
            if ( ! $calc->hasClass($className)) {
828
                $class = $this->_em->getClassMetadata($className);
romanb's avatar
romanb committed
829
                $calc->addClass($class);
830
                $newNodes[] = $class;
831 832 833 834
            }
        }

        // Calculate dependencies for new nodes
835
        foreach ($newNodes as $class) {
836
            foreach ($class->associationMappings as $assoc) {
837
                if ($assoc->isOwningSide && $assoc->isOneToOne()) {
838
                    $targetClass = $this->_em->getClassMetadata($assoc->targetEntityName);
romanb's avatar
romanb committed
839 840
                    if ( ! $calc->hasClass($targetClass->name)) {
                        $calc->addClass($targetClass);
841
                    }
romanb's avatar
romanb committed
842
                    $calc->addDependency($targetClass, $class);
843 844 845 846
                }
            }
        }

romanb's avatar
romanb committed
847
        return $calc->getCommitOrder();
848 849
    }

850
    /**
romanb's avatar
romanb committed
851
     * Schedules an entity for insertion into the database.
852
     * If the entity already has an identifier, it will be added to the identity map.
853
     *
854
     * @param object $entity The entity to schedule for insertion.
855
     */
romanb's avatar
romanb committed
856
    public function scheduleForInsert($entity)
857
    {
858
        $oid = spl_object_hash($entity);
859

860
        if (isset($this->_entityUpdates[$oid])) {
romanb's avatar
romanb committed
861
            throw new \InvalidArgumentException("Dirty entity can not be scheduled for insertion.");
862
        }
863
        if (isset($this->_entityDeletions[$oid])) {
romanb's avatar
romanb committed
864
            throw new \InvalidArgumentException("Removed entity can not be scheduled for insertion.");
865
        }
866
        if (isset($this->_entityInsertions[$oid])) {
romanb's avatar
romanb committed
867
            throw new \InvalidArgumentException("Entity can not be scheduled for insertion twice.");
868
        }
869

870
        $this->_entityInsertions[$oid] = $entity;
romanb's avatar
romanb committed
871

872
        if (isset($this->_entityIdentifiers[$oid])) {
873 874
            $this->addToIdentityMap($entity);
        }
875
    }
876 877

    /**
878
     * Checks whether an entity is scheduled for insertion.
879
     *
880
     * @param object $entity
881 882
     * @return boolean
     */
romanb's avatar
romanb committed
883
    public function isScheduledForInsert($entity)
884
    {
885
        return isset($this->_entityInsertions[spl_object_hash($entity)]);
886
    }
887

888
    /**
889
     * Schedules an entity for being updated.
890
     *
891
     * @param object $entity The entity to schedule for being updated.
892
     */
romanb's avatar
romanb committed
893
    public function scheduleForUpdate($entity)
894
    {
895 896
        $oid = spl_object_hash($entity);
        if ( ! isset($this->_entityIdentifiers[$oid])) {
romanb's avatar
romanb committed
897
            throw new \InvalidArgumentException("Entity has no identity.");
898
        }
899
        if (isset($this->_entityDeletions[$oid])) {
romanb's avatar
romanb committed
900
            throw new \InvalidArgumentException("Entity is removed.");
901
        }
902

903 904
        if ( ! isset($this->_entityUpdates[$oid]) && ! isset($this->_entityInsertions[$oid])) {
            $this->_entityUpdates[$oid] = $entity;
905
        }
906
    }
907 908
    
    /**
909
     * INTERNAL:
910
     * Schedules an extra update that will be executed immediately after the
911
     * regular entity updates within the currently running commit cycle.
912
     * 
romanb's avatar
romanb committed
913 914
     * Extra updates for entities are stored as (entity, changeset) tuples.
     * 
romanb's avatar
romanb committed
915
     * @ignore
romanb's avatar
romanb committed
916 917
     * @param object $entity The entity for which to schedule an extra update.
     * @param array $changeset The changeset of the entity (what to update).
918
     */
919 920
    public function scheduleExtraUpdate($entity, array $changeset)
    {
romanb's avatar
romanb committed
921 922 923 924 925 926 927
        $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);
        }
928 929
    }

930 931 932 933 934
    /**
     * 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.
     *
935
     * @param object $entity
936 937
     * @return boolean
     */
romanb's avatar
romanb committed
938
    public function isScheduledForUpdate($entity)
939
    {
940
        return isset($this->_entityUpdates[spl_object_hash($entity)]);
941
    }
942 943

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

960 961 962
        if ( ! $this->isInIdentityMap($entity)) {
            return; // ignore
        }
963

964
        $this->removeFromIdentityMap($entity);
romanb's avatar
romanb committed
965

966 967
        if (isset($this->_entityUpdates[$oid])) {
            unset($this->_entityUpdates[$oid]);
romanb's avatar
romanb committed
968
        }
969 970
        if ( ! isset($this->_entityDeletions[$oid])) {
            $this->_entityDeletions[$oid] = $entity;
971
        }
972 973
    }

974
    /**
975 976
     * Checks whether an entity is registered as removed/deleted with the unit
     * of work.
977
     *
978
     * @param object $entity
979
     * @return boolean
980
     */
romanb's avatar
romanb committed
981
    public function isScheduledForDelete($entity)
982
    {
983
        return isset($this->_entityDeletions[spl_object_hash($entity)]);
984
    }
985

986
    /**
romanb's avatar
romanb committed
987
     * Checks whether an entity is scheduled for insertion, update or deletion.
988 989
     * 
     * @param $entity
romanb's avatar
romanb committed
990
     * @return boolean
991
     */
romanb's avatar
romanb committed
992
    public function isEntityScheduled($entity)
993
    {
994
        $oid = spl_object_hash($entity);
995 996 997
        return isset($this->_entityInsertions[$oid]) ||
                isset($this->_entityUpdates[$oid]) ||
                isset($this->_entityDeletions[$oid]);
998
    }
999

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

1029 1030
    /**
     * Gets the state of an entity within the current unit of work.
1031 1032 1033 1034
     * 
     * 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.
1035
     *
1036
     * @param object $entity
1037 1038 1039
     * @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.
1040
     * @return int The entity state.
1041
     */
1042
    public function getEntityState($entity, $assume = null)
1043
    {
1044
        $oid = spl_object_hash($entity);
romanb's avatar
romanb committed
1045
        if ( ! isset($this->_entityStates[$oid])) {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            // 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
1057
            } else {
1058
                $this->_entityStates[$oid] = $assume;
romanb's avatar
romanb committed
1059 1060 1061
            }
        }
        return $this->_entityStates[$oid];
1062 1063
    }

romanb's avatar
romanb committed
1064
    /**
1065
     * INTERNAL:
romanb's avatar
romanb committed
1066 1067
     * Removes an entity from the identity map. This effectively detaches the
     * entity from the persistence management of Doctrine.
romanb's avatar
romanb committed
1068
     *
romanb's avatar
romanb committed
1069
     * @ignore
1070
     * @param object $entity
1071
     * @return boolean
romanb's avatar
romanb committed
1072
     */
1073
    public function removeFromIdentityMap($entity)
1074
    {
romanb's avatar
romanb committed
1075
        $oid = spl_object_hash($entity);
1076
        $classMetadata = $this->_em->getClassMetadata(get_class($entity));
1077
        $idHash = implode(' ', $this->_entityIdentifiers[$oid]);
1078
        if ($idHash === '') {
romanb's avatar
romanb committed
1079
            throw new \InvalidArgumentException("The given entity has no identity.");
1080
        }
1081
        $className = $classMetadata->rootEntityName;
1082 1083
        if (isset($this->_identityMap[$className][$idHash])) {
            unset($this->_identityMap[$className][$idHash]);
romanb's avatar
romanb committed
1084
            $this->_entityStates[$oid] = self::STATE_DETACHED;
1085 1086 1087 1088 1089
            return true;
        }

        return false;
    }
1090

romanb's avatar
romanb committed
1091
    /**
1092
     * INTERNAL:
romanb's avatar
romanb committed
1093
     * Gets an entity in the identity map by its identifier hash.
romanb's avatar
romanb committed
1094
     *
romanb's avatar
romanb committed
1095
     * @ignore
1096 1097
     * @param string $idHash
     * @param string $rootClassName
1098
     * @return object
romanb's avatar
romanb committed
1099
     */
1100
    public function getByIdHash($idHash, $rootClassName)
1101
    {
1102 1103
        return $this->_identityMap[$rootClassName][$idHash];
    }
1104 1105

    /**
1106
     * INTERNAL:
1107 1108 1109
     * 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
1110
     * @ignore
romanb's avatar
romanb committed
1111 1112
     * @param string $idHash
     * @param string $rootClassName
1113 1114
     * @return mixed The found entity or FALSE.
     */
1115 1116
    public function tryGetByIdHash($idHash, $rootClassName)
    {
romanb's avatar
romanb committed
1117 1118
        return isset($this->_identityMap[$rootClassName][$idHash]) ?
                $this->_identityMap[$rootClassName][$idHash] : false;
1119
    }
1120

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

romanb's avatar
romanb committed
1142
    /**
1143
     * INTERNAL:
romanb's avatar
romanb committed
1144 1145
     * Checks whether an identifier hash exists in the identity map.
     *
romanb's avatar
romanb committed
1146
     * @ignore
romanb's avatar
romanb committed
1147 1148 1149 1150
     * @param string $idHash
     * @param string $rootClassName
     * @return boolean
     */
1151
    public function containsIdHash($idHash, $rootClassName)
1152
    {
1153
        return isset($this->_identityMap[$rootClassName][$idHash]);
1154
    }
1155 1156

    /**
1157
     * Persists an entity as part of the current unit of work.
1158
     *
1159
     * @param object $entity The entity to persist.
1160
     */
romanb's avatar
romanb committed
1161
    public function persist($entity)
1162 1163
    {
        $visited = array();
romanb's avatar
romanb committed
1164
        $this->_doPersist($entity, $visited);
1165 1166 1167 1168 1169 1170
    }

    /**
     * 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.
1171 1172
     * 
     * NOTE: This method always considers entities with a manually assigned identifier as NEW.
1173
     *
1174
     * @param object $entity The entity to persist.
romanb's avatar
romanb committed
1175
     * @param array $visited The already visited entities.
1176
     */
romanb's avatar
romanb committed
1177
    private function _doPersist($entity, array &$visited)
1178
    {
1179
        $oid = spl_object_hash($entity);
1180
        if (isset($visited[$oid])) {
1181 1182 1183
            return; // Prevent infinite recursion
        }

1184
        $visited[$oid] = $entity; // Mark visited
1185

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

    /**
     * Deletes an entity as part of the current unit of work.
     *
1240
     * @param object $entity The entity to remove.
1241
     */
romanb's avatar
romanb committed
1242
    public function remove($entity)
1243
    {
1244
        $visited = array();
romanb's avatar
romanb committed
1245
        $this->_doRemove($entity, $visited);
1246
    }
1247

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

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

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

romanb's avatar
romanb committed
1289
        $this->_cascadeRemove($entity, $visited);
1290 1291
    }

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
    /**
     * 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.
1310 1311 1312
     * @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.
1313 1314 1315 1316 1317 1318 1319
     */
    private function _doMerge($entity, array &$visited, $prevManagedCopy = null, $assoc = null)
    {
        $class = $this->_em->getClassMetadata(get_class($entity));
        $id = $class->getIdentifierValues($entity);

        if ( ! $id) {
1320 1321
            throw new \InvalidArgumentException('New entity detected during merge.'
                    . ' Persist the new entity before merging.');
1322
        }
1323
        
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        // 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);
1339
            }
1340 1341 1342 1343
            
            if ($managedCopy === null) {
                throw new \InvalidArgumentException('New entity detected during merge.'
                        . ' Persist the new entity before merging.');
1344
            }
1345 1346 1347 1348 1349
            
            if ($class->isVersioned) {
                $managedCopyVersion = $class->reflFields[$class->versionField]->getValue($managedCopy);
                $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
                // Throw exception if versions dont match.
1350
                if ($managedCopyVersion != $entityVersion) {
1351
                    throw OptimisticLockException::lockFailed();
1352 1353 1354 1355 1356 1357 1358 1359 1360
                }
            }
    
            // 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];
1361 1362 1363 1364 1365 1366 1367 1368
                    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);
1369
                                $this->registerManaged($proxy, $id, array());
1370 1371
                            }
                        }
1372 1373
                    } else {
                        $coll = new PersistentCollection($this->_em,
1374 1375
                                $this->_em->getClassMetadata($assoc2->targetEntityName),
                                new ArrayCollection
1376 1377 1378 1379 1380 1381 1382
                                );
                        $coll->setOwner($managedCopy, $assoc2);
                        $coll->setInitialized($assoc2->isCascadeMerge);
                        $prop->setValue($managedCopy, $coll);
                    }
                }
                if ($class->isChangeTrackingNotify()) {
1383
                    //TODO: put changed fields in changeset...?
1384 1385 1386
                }
            }
            if ($class->isChangeTrackingDeferredExplicit()) {
1387
                //TODO: Mark $managedCopy for dirty check...? ($this->_scheduledForDirtyCheck)
1388 1389 1390 1391
            }
        }

        if ($prevManagedCopy !== null) {
romanb's avatar
romanb committed
1392
            $assocField = $assoc->sourceFieldName;
1393 1394
            $prevClass = $this->_em->getClassMetadata(get_class($prevManagedCopy));
            if ($assoc->isOneToOne()) {
1395
                $prevClass->reflFields[$assocField]->setValue($prevManagedCopy, $managedCopy);
1396
                //TODO: What about back-reference if bidirectional?
1397
            } else {
1398 1399 1400 1401
                $prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->unwrap()->add($managedCopy);
                if ($assoc->isOneToMany()) {
                    $class->reflFields[$assoc->mappedByFieldName]->setValue($managedCopy, $prevManagedCopy);
                }
1402 1403 1404 1405 1406 1407 1408
            }
        }

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

        return $managedCopy;
    }
romanb's avatar
romanb committed
1409
    
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    /**
     * 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
1443
                        $this->_entityStates[$oid], $this->_originalEntityData[$oid]);
1444 1445 1446 1447 1448 1449 1450 1451 1452
                break;
            case self::STATE_NEW:
            case self::STATE_DETACHED:
                return;
        }
        
        $this->_cascadeDetach($entity, $visited);
    }
    
romanb's avatar
romanb committed
1453
    /**
1454 1455
     * Refreshes the state of the given entity from the database, overwriting
     * any local, unpersisted changes.
romanb's avatar
romanb committed
1456
     * 
1457
     * @param object $entity The entity to refresh.
1458
     * @throws InvalidArgumentException If the entity is not MANAGED.
romanb's avatar
romanb committed
1459 1460 1461 1462
     */
    public function refresh($entity)
    {
        $visited = array();
1463
        $this->_doRefresh($entity, $visited);
romanb's avatar
romanb committed
1464 1465 1466 1467 1468 1469 1470
    }
    
    /**
     * Executes a refresh operation on an entity.
     * 
     * @param object $entity The entity to refresh.
     * @param array $visited The already visited entities during cascades.
1471
     * @throws InvalidArgumentException If the entity is not MANAGED.
romanb's avatar
romanb committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
     */
    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));
1483 1484 1485 1486 1487 1488 1489
        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
1490
        }
1491
        
romanb's avatar
romanb committed
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
        $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
1504 1505
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadeRefresh) {
romanb's avatar
romanb committed
1506 1507
                continue;
            }
romanb's avatar
romanb committed
1508
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1509
            if ($relatedEntities instanceof Collection) {
romanb's avatar
romanb committed
1510 1511 1512 1513
                if ($relatedEntities instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                }
romanb's avatar
romanb committed
1514 1515 1516 1517 1518 1519 1520 1521
                foreach ($relatedEntities as $relatedEntity) {
                    $this->_doRefresh($relatedEntity, $visited);
                }
            } else if ($relatedEntities !== null) {
                $this->_doRefresh($relatedEntities, $visited);
            }
        }
    }
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
    
    /**
     * 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
1532 1533
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadeDetach) {
1534 1535
                continue;
            }
romanb's avatar
romanb committed
1536
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1537
            if ($relatedEntities instanceof Collection) {
1538 1539 1540 1541
                if ($relatedEntities instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                }
1542 1543 1544 1545 1546 1547 1548 1549
                foreach ($relatedEntities as $relatedEntity) {
                    $this->_doDetach($relatedEntity, $visited);
                }
            } else if ($relatedEntities !== null) {
                $this->_doDetach($relatedEntities, $visited);
            }
        }
    }
1550 1551 1552

    /**
     * Cascades a merge operation to associated entities.
1553
     *
1554 1555 1556
     * @param object $entity
     * @param object $managedCopy
     * @param array $visited
1557 1558 1559 1560
     */
    private function _cascadeMerge($entity, $managedCopy, array &$visited)
    {
        $class = $this->_em->getClassMetadata(get_class($entity));
romanb's avatar
romanb committed
1561 1562
        foreach ($class->associationMappings as $assoc) {
            if ( ! $assoc->isCascadeMerge) {
1563 1564
                continue;
            }
romanb's avatar
romanb committed
1565
            $relatedEntities = $class->reflFields[$assoc->sourceFieldName]->getValue($entity);
1566
            if ($relatedEntities instanceof Collection) {
1567 1568 1569 1570
                if ($relatedEntities instanceof PersistentCollection) {
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                }
1571
                foreach ($relatedEntities as $relatedEntity) {
romanb's avatar
romanb committed
1572
                    $this->_doMerge($relatedEntity, $visited, $managedCopy, $assoc);
1573
                }
1574
            } else if ($relatedEntities !== null) {
romanb's avatar
romanb committed
1575
                $this->_doMerge($relatedEntities, $visited, $managedCopy, $assoc);
1576 1577 1578 1579
            }
        }
    }

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

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

    /**
     * Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
     *
     * @return Doctrine\ORM\Internal\CommitOrderCalculator
     */
1639 1640
    public function getCommitOrderCalculator()
    {
romanb's avatar
romanb committed
1641 1642 1643
        if ($this->_commitOrderCalculator === null) {
            $this->_commitOrderCalculator = new Internal\CommitOrderCalculator;
        }
1644 1645 1646
        return $this->_commitOrderCalculator;
    }

romanb's avatar
romanb committed
1647
    /**
1648
     * Clears the UnitOfWork.
romanb's avatar
romanb committed
1649
     */
1650
    public function clear()
1651
    {
romanb's avatar
romanb committed
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
        $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
1663
        $this->_extraUpdates =
romanb's avatar
romanb committed
1664
        $this->_orphanRemovals = array();
romanb's avatar
romanb committed
1665 1666 1667
        if ($this->_commitOrderCalculator !== null) {
            $this->_commitOrderCalculator->clear();
        }
1668
    }
1669 1670 1671 1672 1673 1674 1675
    
    /**
     * 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
1676
     * @ignore
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
     * @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
     */
1690
    public function scheduleCollectionDeletion(PersistentCollection $coll)
romanb's avatar
romanb committed
1691 1692 1693 1694 1695
    {
        //TODO: if $coll is already scheduled for recreation ... what to do?
        // Just remove $coll from the scheduled recreations?
        $this->_collectionDeletions[] = $coll;
    }
1696

1697
    public function isCollectionScheduledForDeletion(PersistentCollection $coll)
romanb's avatar
romanb committed
1698
    {
1699
        return in_array($coll, $this->_collectionsDeletions, true);
romanb's avatar
romanb committed
1700
    }
1701

1702
    /**
1703
     * INTERNAL:
1704
     * Creates an entity. Used for reconstitution of entities during hydration.
1705
     *
romanb's avatar
romanb committed
1706
     * @ignore
1707 1708 1709 1710
     * @param string $className The name of the entity class.
     * @param array $data The data for the entity.
     * @param array $hints Any hints to account for during reconstitution/lookup of the entity.
     * @return object The entity instance.
romanb's avatar
romanb committed
1711
     * @internal Highly performance-sensitive method.
1712
     * 
1713
     * @todo Rename: getOrCreateEntity
1714
     */
1715
    public function createEntity($className, array $data, &$hints = array())
1716
    {
1717
        $class = $this->_em->getClassMetadata($className);
1718
        //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]);
1719

1720 1721 1722
        if ($class->isIdentifierComposite) {
            $id = array();
            foreach ($class->identifier as $fieldName) {
1723
                $id[$fieldName] = $data[$fieldName];
1724
            }
1725
            $idHash = implode(' ', $id);
1726
        } else {
1727 1728
            $idHash = $data[$class->identifier[0]];
            $id = array($class->identifier[0] => $idHash);
1729
        }
1730 1731 1732

        if (isset($this->_identityMap[$class->rootEntityName][$idHash])) {
            $entity = $this->_identityMap[$class->rootEntityName][$idHash];
1733
            $oid = spl_object_hash($entity);
1734 1735 1736 1737 1738 1739
            if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
                $entity->__isInitialized__ = true;
                $overrideLocalValues = true;
            } else {
                $overrideLocalValues = isset($hints[Query::HINT_REFRESH]);
            }
1740
        } else {
1741
            $entity = $class->newInstance();
1742 1743
            $oid = spl_object_hash($entity);
            $this->_entityIdentifiers[$oid] = $id;
1744
            $this->_entityStates[$oid] = self::STATE_MANAGED;
1745
            $this->_originalEntityData[$oid] = $data;
1746
            $this->_identityMap[$class->rootEntityName][$idHash] = $entity;
romanb's avatar
romanb committed
1747
            if ($entity instanceof NotifyPropertyChanged) {
1748 1749
                $entity->addPropertyChangedListener($this);
            }
1750
            $overrideLocalValues = true;
1751 1752
        }

1753
        if ($overrideLocalValues) {
1754 1755 1756 1757 1758 1759 1760
            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);
                    }
1761
                }
1762
            }
1763 1764 1765 1766
            
            // 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) {
1767
                    // Check if the association is not among the fetch-joined associations already.
romanb's avatar
romanb committed
1768
                    if (isset($hints['fetched'][$className][$field])) {
1769 1770
                        continue;
                    }
romanb's avatar
romanb committed
1771

1772
                    $targetClass = $this->_em->getClassMetadata($assoc->targetEntityName);
1773

1774 1775 1776 1777 1778 1779
                    if ($assoc->isOneToOne()) {
                        if ($assoc->isOwningSide) {
                            $associatedId = array();
                            foreach ($assoc->targetToSourceKeyColumns as $targetColumn => $srcColumn) {
                                $joinColumnValue = $data[$srcColumn];
                                if ($joinColumnValue !== null) {
1780
                                    $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
1781
                                }
1782 1783
                            }
                            if ( ! $associatedId) {
1784
                                // Foreign key is NULL
1785 1786 1787
                                $class->reflFields[$field]->setValue($entity, null);
                                $this->_originalEntityData[$oid][$field] = null;
                            } else {
1788
                                // Foreign key is set
1789 1790 1791 1792 1793 1794
                                // 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];
1795
                                } else {
1796 1797 1798 1799 1800 1801 1802 1803
                                    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;
                                    }
1804
                                }
1805 1806
                                $this->_originalEntityData[$oid][$field] = $newValue;
                                $class->reflFields[$field]->setValue($entity, $newValue);
1807 1808
                            }
                        } else {
1809 1810
                            // Inverse side of x-to-one can never be lazy
                            $class->reflFields[$field]->setValue($entity, $assoc->load($entity, null, $this->_em));
1811 1812 1813 1814 1815 1816
                        }
                    } else {
                        // Inject collection
                        $reflField = $class->reflFields[$field];
                        $pColl = new PersistentCollection(
                            $this->_em, $targetClass,
1817
                            //TODO: getValue might be superfluous once DDC-79 is implemented. 
1818 1819 1820 1821 1822 1823 1824 1825
                            $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);
1826
                        }
1827
                        $this->_originalEntityData[$oid][$field] = $pColl;
1828 1829 1830
                    }
                }
            }
1831
        }
1832
        
1833
        //TODO: These should be invoked later, after hydration, because associations may not yet be loaded here.
1834
        if (isset($class->lifecycleCallbacks[Events::postLoad])) {
1835 1836 1837
            $class->invokeLifecycleCallbacks(Events::postLoad, $entity);
        }
        if ($this->_evm->hasListeners(Events::postLoad)) {
1838
            $this->_evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($entity));
1839
        }
1840 1841

        return $entity;
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
    }

    /**
     * Gets the identity map of the UnitOfWork.
     *
     * @return array
     */
    public function getIdentityMap()
    {
        return $this->_identityMap;
    }
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868

    /**
     * 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();
    }
1869 1870 1871 1872 1873 1874 1875 1876
    
    /**
     * @ignore
     */
    public function setOriginalEntityData($entity, array $data)
    {
        $this->_originalEntityData[spl_object_hash($entity)] = $data;
    }
1877 1878 1879

    /**
     * INTERNAL:
1880
     * Sets a property value of the original data array of an entity.
1881
     *
romanb's avatar
romanb committed
1882
     * @ignore
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
     * @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.
1894
     * The returned value is always an array of identifier values. If the entity
1895
     * has a composite identifier then the identifier values are in the same
1896
     * order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
1897 1898 1899 1900 1901 1902 1903 1904
     *
     * @param object $entity
     * @return array The identifier values.
     */
    public function getEntityIdentifier($entity)
    {
        return $this->_entityIdentifiers[spl_object_hash($entity)];
    }
1905 1906

    /**
1907 1908
     * Tries to find an entity with the given identifier in the identity map of
     * this UnitOfWork.
1909
     *
1910 1911 1912 1913
     * @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.
1914 1915 1916
     */
    public function tryGetById($id, $rootClassName)
    {
1917
        $idHash = implode(' ', (array) $id);
1918 1919 1920 1921 1922
        if (isset($this->_identityMap[$rootClassName][$idHash])) {
            return $this->_identityMap[$rootClassName][$idHash];
        }
        return false;
    }
1923

1924 1925 1926 1927 1928
    /**
     * Schedules an entity for dirty-checking at commit-time.
     *
     * @param object $entity The entity to schedule for dirty-checking.
     */
1929 1930
    public function scheduleForDirtyCheck($entity)
    {
1931
        $rootClassName = $this->_em->getClassMetadata(get_class($entity))->rootEntityName;
1932 1933 1934
        $this->_scheduledForDirtyCheck[$rootClassName] = $entity;
    }

1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
    /**
     * 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);
    }

1945 1946 1947
    /**
     * Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
     * number of entities in the identity map.
1948 1949
     *
     * @return integer
1950 1951 1952 1953
     */
    public function size()
    {
        $count = 0;
romanb's avatar
romanb committed
1954 1955 1956
        foreach ($this->_identityMap as $entitySet) {
            $count += count($entitySet);
        }
1957 1958
        return $count;
    }
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969

    /**
     * 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);
1970
            if ($class->isInheritanceTypeNone()) {
1971
                $persister = new Persisters\StandardEntityPersister($this->_em, $class);
1972 1973 1974
            } else if ($class->isInheritanceTypeSingleTable()) {
                $persister = new Persisters\SingleTablePersister($this->_em, $class);
            } else if ($class->isInheritanceTypeJoined()) {
1975
                $persister = new Persisters\JoinedSubclassPersister($this->_em, $class);
1976
            } else {
1977
                $persister = new Persisters\UnionSubclassPersister($this->_em, $class);
1978 1979 1980 1981 1982 1983
            }
            $this->_persisters[$entityName] = $persister;
        }
        return $this->_persisters[$entityName];
    }

1984 1985 1986 1987 1988 1989
    /**
     * Gets a collection persister for a collection-valued association.
     *
     * @param AssociationMapping $association
     * @return AbstractCollectionPersister
     */
1990 1991 1992 1993
    public function getCollectionPersister($association)
    {
        $type = get_class($association);
        if ( ! isset($this->_collectionPersisters[$type])) {
1994 1995 1996 1997
            if ($association instanceof Mapping\OneToManyMapping) {
                $persister = new Persisters\OneToManyPersister($this->_em);
            } else if ($association instanceof Mapping\ManyToManyMapping) {
                $persister = new Persisters\ManyToManyPersister($this->_em);
1998 1999 2000 2001 2002
            }
            $this->_collectionPersisters[$type] = $persister;
        }
        return $this->_collectionPersisters[$type];
    }
2003

2004 2005 2006 2007 2008 2009 2010 2011
    /**
     * 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
2012
    public function registerManaged($entity, array $id, array $data)
2013 2014 2015 2016 2017 2018 2019
    {
        $oid = spl_object_hash($entity);
        $this->_entityIdentifiers[$oid] = $id;
        $this->_entityStates[$oid] = self::STATE_MANAGED;
        $this->_originalEntityData[$oid] = $data;
        $this->addToIdentityMap($entity);
    }
2020

2021 2022 2023 2024 2025 2026 2027 2028
    /**
     * 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
2029
        unset($this->_entityChangeSets[$oid]);
2030
    }
2031

2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
    /* 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)
    {
2044 2045
        $oid = spl_object_hash($entity);
        $class = $this->_em->getClassMetadata(get_class($entity));
2046

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

2049 2050 2051
        if (isset($class->associationMappings[$propertyName])) {
            $assoc = $class->associationMappings[$propertyName];
            if ($assoc->isOneToOne() && $assoc->isOwningSide) {
2052
                $this->_entityUpdates[$oid] = $entity;
2053 2054 2055 2056 2057
            } else if ($oldValue instanceof PersistentCollection) {
                // A PersistentCollection was de-referenced, so delete it.
                if  ( ! in_array($oldValue, $this->_collectionDeletions, true)) {
                    $this->_collectionDeletions[] = $oldValue;
                }
2058
            }
2059 2060
        } else {
            $this->_entityUpdates[$oid] = $entity;
2061
        }
2062
    }
2063
}