1
0
mirror of synced 2024-12-14 23:26:04 +03:00
doctrine2/lib/Doctrine/ORM/UnitOfWork.php

3306 lines
111 KiB
PHP
Raw Normal View History

<?php
/*
* 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
2012-05-26 16:37:00 +04:00
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM;
2012-10-12 15:53:20 +04:00
use Exception;
use InvalidArgumentException;
use UnexpectedValueException;
2012-07-31 05:26:55 +04:00
2012-10-12 15:53:20 +04:00
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\NotifyPropertyChanged;
use Doctrine\Common\PropertyChangedListener;
use Doctrine\Common\Persistence\ObjectManagerAware;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Proxy\Proxy;
2012-07-31 05:26:55 +04:00
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Event\PreFlushEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\ListenersInvoker;
2012-07-31 05:26:55 +04:00
2013-02-14 02:42:13 +04:00
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\Persisters\BasicEntityPersister;
use Doctrine\ORM\Persisters\SingleTablePersister;
use Doctrine\ORM\Persisters\JoinedSubclassPersister;
use Doctrine\ORM\Persisters\OneToManyPersister;
use Doctrine\ORM\Persisters\ManyToManyPersister;
/**
* The UnitOfWork is responsible for tracking changes to objects during an
* "object-level" transaction and for writing out changes to the database
* in the correct order.
*
* @since 2.0
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
2008-02-24 01:04:39 +03:00
* @author Roman Borschel <roman@code-factory.org>
* @internal This class contains highly performance-sensitive code.
*/
class UnitOfWork implements PropertyChangedListener
{
/**
* An entity is in MANAGED state when its persistence is managed by an EntityManager.
*/
const STATE_MANAGED = 1;
/**
* An entity is new if it has just been instantiated (i.e. using the "new" operator)
* and is not (yet) managed by an EntityManager.
*/
const STATE_NEW = 2;
/**
* A detached entity is an instance with persistent state and identity that is not
* (or no longer) associated with an EntityManager (and a UnitOfWork).
*/
const STATE_DETACHED = 3;
/**
* A removed entity instance is an instance with a persistent identity,
* associated with an EntityManager, whose persistent state will be deleted
* on commit.
*/
const STATE_REMOVED = 4;
2013-04-08 13:27:22 +04:00
/**
* Hint used to collect all primary keys of associated entities during hydration
* and execute it in a dedicated query afterwards
* @see https://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html?highlight=eager#temporarily-change-fetch-mode-in-dql
*/
const HINT_DEFEREAGERLOAD = 'deferEagerLoad';
2008-02-24 01:04:39 +03:00
/**
* The identity map that holds references to all managed entities that have
* an identity. The entities are grouped by their class name.
* Since all classes in a hierarchy must share the same identifier set,
* we always take the root class name of the hierarchy.
2008-02-24 01:04:39 +03:00
*
* @var array
2008-02-24 01:04:39 +03:00
*/
private $identityMap = array();
/**
* Map of all identifiers of managed entities.
* Keys are object ids (spl_object_hash).
*
* @var array
*/
private $entityIdentifiers = array();
/**
* Map of the original entity data of managed entities.
2009-07-19 20:54:53 +04:00
* Keys are object ids (spl_object_hash). This is used for calculating changesets
* at commit time.
*
* @var array
2009-07-19 20:54:53 +04:00
* @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.
*/
private $originalEntityData = array();
/**
* Map of entity changes. Keys are object ids (spl_object_hash).
* Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
*
* @var array
*/
private $entityChangeSets = array();
/**
* The (cached) states of any known entities.
2009-07-19 20:54:53 +04:00
* Keys are object ids (spl_object_hash).
*
* @var array
*/
private $entityStates = array();
2009-01-29 20:00:44 +03:00
/**
* Map of entities that are scheduled for dirty checking at commit time.
* This is only used for entities with a change tracking policy of DEFERRED_EXPLICIT.
2009-07-19 20:54:53 +04:00
* Keys are object ids (spl_object_hash).
*
2009-07-19 20:54:53 +04:00
* @var array
* @todo rename: scheduledForSynchronization
2009-01-29 20:00:44 +03:00
*/
private $scheduledForDirtyCheck = array();
2009-01-29 20:00:44 +03:00
2008-02-24 01:04:39 +03:00
/**
* A list of all pending entity insertions.
*
* @var array
2008-02-24 01:04:39 +03:00
*/
private $entityInsertions = array();
2008-02-24 01:04:39 +03:00
/**
* A list of all pending entity updates.
*
* @var array
2008-02-24 01:04:39 +03:00
*/
private $entityUpdates = array();
/**
* Any pending extra updates that have been scheduled by persisters.
*
* @var array
*/
private $extraUpdates = array();
2008-02-24 01:04:39 +03:00
/**
* A list of all pending entity deletions.
*
* @var array
2008-02-24 01:04:39 +03:00
*/
private $entityDeletions = array();
2008-08-16 23:40:59 +04:00
/**
* All pending collection deletions.
2008-08-16 23:40:59 +04:00
*
* @var array
*/
private $collectionDeletions = array();
2008-08-16 23:40:59 +04:00
/**
* All pending collection updates.
2008-08-16 23:40:59 +04:00
*
* @var array
*/
private $collectionUpdates = array();
/**
* List of collections visited during changeset calculation on a commit-phase of a UnitOfWork.
* At the end of the UnitOfWork all these collections will make new snapshots
* of their data.
*
* @var array
*/
private $visitedCollections = array();
/**
* The EntityManager that "owns" this UnitOfWork instance.
*
* @var \Doctrine\ORM\EntityManager
*/
private $em;
2008-02-24 01:04:39 +03:00
/**
* The calculator used to calculate the order in which changes to
* entities need to be written to the database.
2008-02-24 01:04:39 +03:00
*
* @var \Doctrine\ORM\Internal\CommitOrderCalculator
2008-02-24 01:04:39 +03:00
*/
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();
/**
* The EventManager used for dispatching events.
*
* @var \Doctrine\Common\EventManager
*/
private $evm;
2012-08-13 05:10:47 +04:00
/**
* The ListenersInvoker used for dispatching events.
2012-08-13 05:10:47 +04:00
*
* @var \Doctrine\ORM\Event\ListenersInvoker
2012-08-13 05:10:47 +04:00
*/
private $listenersInvoker;
2012-08-13 05:10:47 +04:00
/**
* Orphaned entities that are scheduled for removal.
*
* @var array
*/
private $orphanRemovals = array();
/**
* Read-Only objects are never evaluated
*
* @var array
*/
private $readOnlyObjects = array();
/**
* Map of Entity Class-Names and corresponding IDs that should eager loaded when requested.
*
* @var array
*/
private $eagerLoadingEntities = array();
2013-02-14 02:42:13 +04:00
/**
* @var boolean
*/
protected $hasCache = false;
/**
* Initializes a new UnitOfWork instance, bound to the given EntityManager.
*
* @param \Doctrine\ORM\EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
$this->evm = $em->getEventManager();
$this->listenersInvoker = new ListenersInvoker($em);
2013-02-14 02:42:13 +04:00
$this->hasCache = $em->getConfiguration()->isSecondLevelCacheEnabled();
}
2008-02-24 01:04:39 +03:00
/**
2009-01-29 20:00:44 +03:00
* Commits the UnitOfWork, executing all operations that have been postponed
* up to this point. The state of all managed entities will be synchronized with
* the database.
*
2009-10-07 16:39:46 +04:00
* The operations are executed in the following order:
*
2009-10-07 16:39:46 +04:00
* 1) All entity insertions
* 2) All entity updates
* 3) All collection deletions
* 4) All collection updates
* 5) All entity deletions
*
* @param null|object|array $entity
*
* @return void
2012-12-01 20:28:06 +04:00
*
* @throws \Exception
2008-02-24 01:04:39 +03:00
*/
public function commit($entity = null)
{
// Raise preFlush
if ($this->evm->hasListeners(Events::preFlush)) {
2012-07-31 05:26:55 +04:00
$this->evm->dispatchEvent(Events::preFlush, new PreFlushEventArgs($this->em));
}
// Compute changes done since last commit.
if ($entity === null) {
$this->computeChangeSets();
} elseif (is_object($entity)) {
$this->computeSingleEntityChangeSet($entity);
} elseif (is_array($entity)) {
foreach ($entity as $object) {
$this->computeSingleEntityChangeSet($object);
}
}
2009-01-29 20:00:44 +03:00
2012-07-23 03:14:02 +04:00
if ( ! ($this->entityInsertions ||
$this->entityDeletions ||
$this->entityUpdates ||
$this->collectionUpdates ||
$this->collectionDeletions ||
$this->orphanRemovals)) {
$this->dispatchOnFlushEvent();
$this->dispatchPostFlushEvent();
return; // Nothing to do.
}
if ($this->orphanRemovals) {
foreach ($this->orphanRemovals as $orphan) {
$this->remove($orphan);
}
}
2012-07-23 03:14:02 +04:00
$this->dispatchOnFlushEvent();
2012-07-23 03:14:02 +04:00
// Now we need a commit order to maintain referential integrity
$commitOrder = $this->getCommitOrder();
2012-07-23 03:14:02 +04:00
$conn = $this->em->getConnection();
$conn->beginTransaction();
2012-07-23 03:14:02 +04:00
try {
if ($this->entityInsertions) {
foreach ($commitOrder as $class) {
$this->executeInserts($class);
}
2012-07-23 03:14:02 +04:00
}
2012-07-23 03:14:02 +04:00
if ($this->entityUpdates) {
foreach ($commitOrder as $class) {
$this->executeUpdates($class);
}
2012-07-23 03:14:02 +04:00
}
2012-07-23 03:14:02 +04:00
// Extra updates that were requested by persisters.
if ($this->extraUpdates) {
$this->executeExtraUpdates();
}
2009-05-19 20:11:08 +04:00
2012-07-23 03:14:02 +04:00
// Collection deletions (deletions of complete collections)
foreach ($this->collectionDeletions as $collectionToDelete) {
$this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
}
2013-02-14 02:42:13 +04:00
2012-07-23 03:14:02 +04:00
// Collection updates (deleteRows, updateRows, insertRows)
foreach ($this->collectionUpdates as $collectionToUpdate) {
$this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
}
2009-05-19 20:11:08 +04:00
2012-07-23 03:14:02 +04:00
// Entity deletions come last and need to be in reverse commit order
if ($this->entityDeletions) {
for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i) {
$this->executeDeletions($commitOrder[$i]);
}
}
2012-07-23 03:14:02 +04:00
$conn->commit();
} catch (Exception $e) {
$this->em->close();
$conn->rollback();
2013-02-14 02:42:13 +04:00
$this->afterTransactionRolledBack();
2012-07-23 03:14:02 +04:00
throw $e;
}
2013-02-14 02:42:13 +04:00
$this->afterTransactionComplete();
2012-07-23 03:14:02 +04:00
// Take new snapshots from visited collections
foreach ($this->visitedCollections as $coll) {
$coll->takeSnapshot();
}
2012-07-23 03:14:02 +04:00
$this->dispatchPostFlushEvent();
2009-01-29 20:00:44 +03:00
// Clear up
$this->entityInsertions =
$this->entityUpdates =
$this->entityDeletions =
$this->extraUpdates =
$this->entityChangeSets =
$this->collectionUpdates =
$this->collectionDeletions =
$this->visitedCollections =
$this->scheduledForDirtyCheck =
$this->orphanRemovals = array();
}
/**
* Computes the changesets of all entities scheduled for insertion.
*
* @return void
*/
private function computeScheduleInsertsChangeSets()
{
foreach ($this->entityInsertions as $entity) {
$class = $this->em->getClassMetadata(get_class($entity));
$this->computeChangeSet($class, $entity);
}
}
/**
* Only flushes the given entity according to a ruleset that keeps the UoW consistent.
*
* 1. All entities scheduled for insertion, (orphan) removals and changes in collections are processed as well!
* 2. Read Only entities are skipped.
* 3. Proxies are skipped.
* 4. Only if entity is properly managed.
*
* @param object $entity
*
* @return void
2012-12-01 20:28:06 +04:00
*
* @throws \InvalidArgumentException
*/
private function computeSingleEntityChangeSet($entity)
{
$state = $this->getEntityState($entity);
if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
throw new \InvalidArgumentException("Entity has to be managed or scheduled for removal for single computation " . self::objToStr($entity));
}
$class = $this->em->getClassMetadata(get_class($entity));
if ($state === self::STATE_MANAGED && $class->isChangeTrackingDeferredImplicit()) {
$this->persist($entity);
}
// Compute changes for INSERTed entities first. This must always happen even in this case.
$this->computeScheduleInsertsChangeSets();
2011-11-05 09:09:14 +04:00
if ($class->isReadOnly) {
return;
}
// Ignore uninitialized proxy objects
if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
return;
}
// Only MANAGED entities that are NOT SCHEDULED FOR INSERTION are processed here.
$oid = spl_object_hash($entity);
if ( ! isset($this->entityInsertions[$oid]) && isset($this->entityStates[$oid])) {
$this->computeChangeSet($class, $entity);
}
}
2009-07-24 15:33:38 +04:00
/**
* Executes any extra updates that have been scheduled.
*/
private function executeExtraUpdates()
{
foreach ($this->extraUpdates as $oid => $update) {
list ($entity, $changeset) = $update;
$this->entityChangeSets[$oid] = $changeset;
$this->getEntityPersister(get_class($entity))->update($entity);
}
}
/**
* Gets the changeset for an entity.
*
* @param object $entity
*
* @return array
*/
public function getEntityChangeSet($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->entityChangeSets[$oid])) {
return $this->entityChangeSets[$oid];
}
return array();
}
/**
2010-03-18 16:43:38 +03:00
* Computes the changes that happened to a single entity.
2009-05-05 22:39:25 +04:00
*
* 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.
*
* @ignore
2012-12-01 20:28:06 +04:00
*
* @internal Don't call from the outside.
2012-12-01 20:28:06 +04:00
*
2009-05-05 22:39:25 +04:00
* @param ClassMetadata $class The class descriptor of the entity.
* @param object $entity The entity for which to compute the changes.
2012-12-01 20:28:06 +04:00
*
* @return void
2009-05-05 22:39:25 +04:00
*/
public function computeChangeSet(ClassMetadata $class, $entity)
2009-05-05 22:39:25 +04:00
{
$oid = spl_object_hash($entity);
if (isset($this->readOnlyObjects[$oid])) {
return;
}
if ( ! $class->isInheritanceTypeNone()) {
$class = $this->em->getClassMetadata(get_class($entity));
}
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preFlush);
2012-11-10 00:14:51 +04:00
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
2012-07-31 05:26:55 +04:00
}
2009-05-05 22:39:25 +04:00
$actualData = array();
2009-05-19 20:24:17 +04:00
foreach ($class->reflFields as $name => $refProp) {
$value = $refProp->getValue($entity);
2011-11-05 09:09:14 +04:00
if ($class->isCollectionValuedAssociation($name) && $value !== null && ! ($value instanceof PersistentCollection)) {
// If $value is not a Collection then use an ArrayCollection.
if ( ! $value instanceof Collection) {
$value = new ArrayCollection($value);
2009-06-14 21:34:28 +04:00
}
2009-05-19 20:24:17 +04:00
$assoc = $class->associationMappings[$name];
2009-05-05 22:39:25 +04:00
// Inject PersistentCollection
2011-11-05 09:09:14 +04:00
$value = new PersistentCollection(
$this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value
);
2011-11-05 09:09:14 +04:00
$value->setOwner($entity, $assoc);
$value->setDirty( ! $value->isEmpty());
2011-11-05 09:09:14 +04:00
$class->reflFields[$name]->setValue($entity, $value);
2011-11-05 09:09:14 +04:00
$actualData[$name] = $value;
2011-11-05 09:09:14 +04:00
continue;
}
2011-11-05 09:09:14 +04:00
if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
$actualData[$name] = $value;
2009-05-05 22:39:25 +04:00
}
}
2009-01-29 20:00:44 +03:00
if ( ! isset($this->originalEntityData[$oid])) {
// Entity is either NEW or MANAGED but not yet fully persisted (only has an id).
// These result in an INSERT.
$this->originalEntityData[$oid] = $actualData;
$changeSet = array();
foreach ($actualData as $propName => $actualValue) {
2011-11-05 09:09:14 +04:00
if ( ! isset($class->associationMappings[$propName])) {
$changeSet[$propName] = array(null, $actualValue);
2011-11-05 09:09:14 +04:00
continue;
}
2011-11-05 09:09:14 +04:00
$assoc = $class->associationMappings[$propName];
2011-11-05 09:09:14 +04:00
if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
$changeSet[$propName] = array(null, $actualValue);
}
}
$this->entityChangeSets[$oid] = $changeSet;
2009-05-05 22:39:25 +04:00
} else {
// Entity is "fully" MANAGED: it was already fully persisted before
// and we have a copy of the original data
2011-11-05 09:09:14 +04:00
$originalData = $this->originalEntityData[$oid];
$isChangeTrackingNotify = $class->isChangeTrackingNotify();
$changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
? $this->entityChangeSets[$oid]
2011-11-05 09:09:14 +04:00
: array();
2009-05-05 22:39:25 +04:00
foreach ($actualData as $propName => $actualValue) {
2011-11-05 09:09:14 +04:00
// skip field, its a partially omitted one!
if ( ! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
continue;
}
2011-11-05 09:09:14 +04:00
$orgValue = $originalData[$propName];
2013-04-06 18:11:52 +04:00
// skip if value haven't changed
if ($orgValue === $actualValue) {
continue;
}
2011-11-05 09:09:14 +04:00
// if regular field
if ( ! isset($class->associationMappings[$propName])) {
if ($isChangeTrackingNotify) {
continue;
}
2011-11-05 09:09:14 +04:00
$changeSet[$propName] = array($orgValue, $actualValue);
2011-11-05 09:09:14 +04:00
continue;
}
$assoc = $class->associationMappings[$propName];
// Persistent collection was exchanged with the "originally"
// created one. This can only mean it was cloned and replaced
// on another entity.
if ($actualValue instanceof PersistentCollection) {
$owner = $actualValue->getOwner();
if ($owner === null) { // cloned
$actualValue->setOwner($entity, $assoc);
} else if ($owner !== $entity) { // no clone, we have to fix
if (!$actualValue->isInitialized()) {
$actualValue->initialize(); // we have to do this otherwise the cols share state
}
$newValue = clone $actualValue;
$newValue->setOwner($entity, $assoc);
$class->reflFields[$propName]->setValue($entity, $newValue);
}
}
2011-11-05 09:09:14 +04:00
if ($orgValue instanceof PersistentCollection) {
// A PersistentCollection was de-referenced, so delete it.
$coid = spl_object_hash($orgValue);
if (isset($this->collectionDeletions[$coid])) {
continue;
}
2011-11-05 09:09:14 +04:00
$this->collectionDeletions[$coid] = $orgValue;
$changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
continue;
}
2011-11-05 09:09:14 +04:00
if ($assoc['type'] & ClassMetadata::TO_ONE) {
if ($assoc['isOwningSide']) {
$changeSet[$propName] = array($orgValue, $actualValue);
}
2011-11-05 09:09:14 +04:00
if ($orgValue !== null && $assoc['orphanRemoval']) {
$this->scheduleOrphanRemoval($orgValue);
}
2009-05-05 22:39:25 +04:00
}
}
2009-05-05 22:39:25 +04:00
if ($changeSet) {
2011-11-05 09:09:14 +04:00
$this->entityChangeSets[$oid] = $changeSet;
$this->originalEntityData[$oid] = $actualData;
2011-11-05 09:09:14 +04:00
$this->entityUpdates[$oid] = $entity;
2009-05-05 22:39:25 +04:00
}
}
2010-05-01 14:14:16 +04:00
2010-03-18 16:43:38 +03:00
// Look for changes in associations of the entity
foreach ($class->associationMappings as $field => $assoc) {
2013-02-14 02:42:13 +04:00
if (($val = $class->reflFields[$field]->getValue($entity)) === null) {
continue;
}
$this->computeAssociationChanges($assoc, $val);
if ( ! isset($this->entityChangeSets[$oid]) &&
$assoc['isOwningSide'] &&
$assoc['type'] == ClassMetadata::MANY_TO_MANY &&
$val instanceof PersistentCollection &&
$val->isDirty()) {
$this->entityChangeSets[$oid] = array();
$this->originalEntityData[$oid] = $actualData;
$this->entityUpdates[$oid] = $entity;
2010-03-18 16:43:38 +03:00
}
}
}
/**
* Computes all the changes that have been done to entities and collections
* since the last commit and stores these changes in the _entityChangeSet map
* temporarily for access by the persisters, until the UoW commit is finished.
2012-12-01 20:28:06 +04:00
*
* @return void
2010-03-18 16:43:38 +03:00
*/
public function computeChangeSets()
{
// Compute changes for INSERTed entities first. This must always happen.
$this->computeScheduleInsertsChangeSets();
2010-03-18 16:43:38 +03:00
// Compute changes for other MANAGED entities. Change tracking policies take effect here.
foreach ($this->identityMap as $className => $entities) {
$class = $this->em->getClassMetadata($className);
2010-03-18 16:43:38 +03:00
2010-07-15 17:52:42 +04:00
// Skip class if instances are read-only
if ($class->isReadOnly) {
continue;
}
2010-03-18 16:43:38 +03:00
2010-07-15 17:52:42 +04:00
// If change tracking is explicit or happens through notification, then only compute
// changes on entities of that type that are explicitly marked for synchronization.
switch (true) {
case ($class->isChangeTrackingDeferredImplicit()):
$entitiesToProcess = $entities;
break;
case (isset($this->scheduledForDirtyCheck[$className])):
$entitiesToProcess = $this->scheduledForDirtyCheck[$className];
break;
default:
$entitiesToProcess = array();
}
2010-03-18 16:43:38 +03:00
foreach ($entitiesToProcess as $entity) {
// Ignore uninitialized proxy objects
if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
continue;
}
2010-03-18 16:43:38 +03:00
// Only MANAGED entities that are NOT SCHEDULED FOR INSERTION are processed here.
$oid = spl_object_hash($entity);
if ( ! isset($this->entityInsertions[$oid]) && isset($this->entityStates[$oid])) {
2010-03-18 16:43:38 +03:00
$this->computeChangeSet($class, $entity);
}
}
}
}
/**
* Computes the changes of an association.
*
2013-02-14 02:42:13 +04:00
* @param array $assoc The association mapping.
* @param mixed $value The value of the association.
*
* @throws ORMInvalidArgumentException
* @throws ORMException
*
* @return void
*/
private function computeAssociationChanges($assoc, $value)
{
2011-11-05 09:09:14 +04:00
if ($value instanceof Proxy && ! $value->__isInitialized__) {
return;
}
if ($value instanceof PersistentCollection && $value->isDirty()) {
$coid = spl_object_hash($value);
if ($assoc['isOwningSide']) {
$this->collectionUpdates[$coid] = $value;
}
$this->visitedCollections[$coid] = $value;
}
// Look through the entities, and in any of their associations,
// for transient (new) entities, recursively. ("Persistence by reachability")
2011-11-05 09:09:14 +04:00
// Unwrap. Uninitialized collections will simply be empty.
$unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? array($value) : $value->unwrap();
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
2011-11-05 09:09:14 +04:00
foreach ($unwrappedValue as $key => $entry) {
$state = $this->getEntityState($entry, self::STATE_NEW);
2012-01-19 08:09:23 +04:00
if ( ! ($entry instanceof $assoc['targetEntity'])) {
2013-02-14 02:42:13 +04:00
throw ORMException::unexpectedAssociationValue($assoc['sourceEntity'], $assoc['fieldName'], get_class($entry), $assoc['targetEntity']);
}
2011-11-05 09:09:14 +04:00
switch ($state) {
case self::STATE_NEW:
if ( ! $assoc['isCascadePersist']) {
2011-12-22 02:56:25 +04:00
throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($assoc, $entry);
2011-11-05 09:09:14 +04:00
}
2011-11-05 09:09:14 +04:00
$this->persistNew($targetClass, $entry);
$this->computeChangeSet($targetClass, $entry);
break;
2011-11-05 09:09:14 +04:00
case self::STATE_REMOVED:
// Consume the $value as array (it's either an array or an ArrayAccess)
2011-11-05 09:09:14 +04:00
// and remove the element from Collection.
if ($assoc['type'] & ClassMetadata::TO_MANY) {
unset($value[$key]);
}
break;
2011-11-05 09:09:14 +04:00
case self::STATE_DETACHED:
// Can actually not happen right now as we assume STATE_NEW,
// so the exception will be raised from the DBAL layer (constraint violation).
2011-12-22 02:56:25 +04:00
throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry);
2011-11-05 09:09:14 +04:00
break;
2011-11-05 09:09:14 +04:00
default:
// MANAGED associated entities are already taken into account
// during changeset calculation anyway, since they are in the identity map.
}
}
}
2010-07-04 20:55:49 +04:00
/**
2012-07-31 05:26:55 +04:00
* @param \Doctrine\ORM\Mapping\ClassMetadata $class
2012-12-01 20:28:06 +04:00
* @param object $entity
*
* @return void
*/
2010-07-04 20:55:49 +04:00
private function persistNew($class, $entity)
{
$oid = spl_object_hash($entity);
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
2012-07-31 05:26:55 +04:00
2012-11-10 00:14:51 +04:00
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
2010-07-04 20:55:49 +04:00
}
$idGen = $class->idGenerator;
2010-07-04 20:55:49 +04:00
if ( ! $idGen->isPostInsertGenerator()) {
$idValue = $idGen->generate($this->em, $entity);
2010-07-04 20:55:49 +04:00
if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
2011-11-05 09:09:14 +04:00
$idValue = array($class->identifier[0] => $idValue);
2011-11-05 09:09:14 +04:00
$class->setIdentifierValues($entity, $idValue);
2010-07-04 20:55:49 +04:00
}
2011-11-05 09:09:14 +04:00
$this->entityIdentifiers[$oid] = $idValue;
2010-07-04 20:55:49 +04:00
}
$this->entityStates[$oid] = self::STATE_MANAGED;
2010-07-04 20:55:49 +04:00
$this->scheduleForInsert($entity);
}
/**
* INTERNAL:
* Computes the changeset of an individual entity, independently of the
* computeChangeSets() routine that is used at the beginning of a UnitOfWork#commit().
*
2009-11-13 19:39:28 +03:00
* 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.
*
2009-10-06 14:04:32 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param ClassMetadata $class The class descriptor of the entity.
* @param object $entity The entity for which to (re)calculate the change set.
*
* @return void
*
* @throws ORMInvalidArgumentException If the passed entity is not MANAGED.
*/
2011-10-10 10:44:17 +04:00
public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity)
{
$oid = spl_object_hash($entity);
if ( ! isset($this->entityStates[$oid]) || $this->entityStates[$oid] != self::STATE_MANAGED) {
throw ORMInvalidArgumentException::entityNotManaged($entity);
2009-11-13 19:39:28 +03:00
}
2011-11-05 09:09:14 +04:00
// skip if change tracking is "NOTIFY"
2009-11-13 22:34:10 +03:00
if ($class->isChangeTrackingNotify()) {
return;
2011-11-05 09:09:14 +04:00
}
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);
}
}
$originalData = $this->originalEntityData[$oid];
2009-11-13 19:39:28 +03:00
$changeSet = array();
foreach ($actualData as $propName => $actualValue) {
$orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
2009-11-13 19:39:28 +03:00
if (is_object($orgValue) && $orgValue !== $actualValue) {
$changeSet[$propName] = array($orgValue, $actualValue);
} else if ($orgValue != $actualValue || ($orgValue === null ^ $actualValue === null)) {
$changeSet[$propName] = array($orgValue, $actualValue);
}
2009-11-13 19:39:28 +03:00
}
if ($changeSet) {
if (isset($this->entityChangeSets[$oid])) {
$this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
}
$this->originalEntityData[$oid] = $actualData;
}
}
2008-09-07 17:48:40 +04:00
/**
* Executes all entity insertions for entities of the specified type.
*
* @param \Doctrine\ORM\Mapping\ClassMetadata $class
2012-12-01 20:28:06 +04:00
*
* @return void
2008-09-07 17:48:40 +04:00
*/
private function executeInserts($class)
{
$entities = array();
$className = $class->name;
$persister = $this->getEntityPersister($className);
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist);
foreach ($this->entityInsertions as $oid => $entity) {
2013-02-14 02:42:13 +04:00
if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
continue;
}
$persister->addInsert($entity);
unset($this->entityInsertions[$oid]);
2012-11-10 00:14:51 +04:00
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$entities[] = $entity;
2009-05-19 20:11:08 +04:00
}
}
2009-12-18 15:30:19 +03:00
2009-05-19 20:11:08 +04:00
$postInsertIds = $persister->executeInserts();
2009-05-19 20:11:08 +04:00
if ($postInsertIds) {
2009-11-13 22:34:10 +03:00
// Persister returned post-insert IDs
2009-05-19 20:11:08 +04:00
foreach ($postInsertIds as $id => $entity) {
$oid = spl_object_hash($entity);
2009-05-19 20:11:08 +04:00
$idField = $class->identifier[0];
2009-05-19 20:11:08 +04:00
$class->reflFields[$idField]->setValue($entity, $id);
$this->entityIdentifiers[$oid] = array($idField => $id);
$this->entityStates[$oid] = self::STATE_MANAGED;
$this->originalEntityData[$oid][$idField] = $id;
2009-05-19 20:11:08 +04:00
$this->addToIdentityMap($entity);
}
}
2012-07-31 05:26:55 +04:00
foreach ($entities as $entity) {
$this->listenersInvoker->invoke($class, Events::postPersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
2009-07-18 22:06:30 +04:00
}
}
2008-09-07 17:48:40 +04:00
/**
* Executes all entity updates for entities of the specified type.
*
* @param \Doctrine\ORM\Mapping\ClassMetadata $class
2012-12-01 20:28:06 +04:00
*
* @return void
2008-09-07 17:48:40 +04:00
*/
private function executeUpdates($class)
{
$className = $class->name;
$persister = $this->getEntityPersister($className);
$preUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preUpdate);
$postUpdateInvoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postUpdate);
foreach ($this->entityUpdates as $oid => $entity) {
2013-02-14 02:42:13 +04:00
if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
continue;
}
if ($preUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::preUpdate, $entity, new PreUpdateEventArgs($entity, $this->em, $this->entityChangeSets[$oid]), $preUpdateInvoke);
$this->recomputeSingleEntityChangeSet($class, $entity);
}
if ( ! empty($this->entityChangeSets[$oid])) {
$persister->update($entity);
}
unset($this->entityUpdates[$oid]);
if ($postUpdateInvoke != ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::postUpdate, $entity, new LifecycleEventArgs($entity, $this->em), $postUpdateInvoke);
}
}
}
2008-09-07 17:48:40 +04:00
/**
* Executes all entity deletions for entities of the specified type.
*
* @param \Doctrine\ORM\Mapping\ClassMetadata $class
2012-12-01 20:28:06 +04:00
*
* @return void
2008-09-07 17:48:40 +04:00
*/
private function executeDeletions($class)
{
$className = $class->name;
$persister = $this->getEntityPersister($className);
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postRemove);
foreach ($this->entityDeletions as $oid => $entity) {
if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
continue;
}
$persister->delete($entity);
unset(
$this->entityDeletions[$oid],
$this->entityIdentifiers[$oid],
$this->originalEntityData[$oid],
$this->entityStates[$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;
if ( ! $class->isIdentifierNatural()) {
$class->reflFields[$class->identifier[0]]->setValue($entity, null);
}
2012-11-10 00:14:51 +04:00
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::postRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
}
}
}
/**
* Gets the commit order.
*
2012-12-01 20:28:06 +04:00
* @param array|null $entityChangeSet
*
* @return array
*/
private function getCommitOrder(array $entityChangeSet = null)
{
if ($entityChangeSet === null) {
$entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
2008-09-07 17:48:40 +04:00
}
2009-12-21 14:06:27 +03:00
$calc = $this->getCommitOrderCalculator();
// See if there are any new classes in the changeset, that are not in the
2013-04-06 18:11:52 +04:00
// commit order graph yet (don't have a node).
// We have to inspect changeSet to be able to correctly build dependencies.
// It is not possible to use IdentityMap here because post inserted ids
// are not yet available.
$newNodes = array();
2012-01-19 08:09:23 +04:00
foreach ($entityChangeSet as $entity) {
$class = $this->em->getClassMetadata(get_class($entity));
if ($calc->hasClass($class->name)) {
continue;
}
$calc->addClass($class);
$newNodes[] = $class;
}
// Calculate dependencies for new nodes
while ($class = array_pop($newNodes)) {
foreach ($class->associationMappings as $assoc) {
if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
continue;
}
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
if ( ! $calc->hasClass($targetClass->name)) {
$calc->addClass($targetClass);
$newNodes[] = $targetClass;
}
$calc->addDependency($targetClass, $class);
// If the target class has mapped subclasses, these share the same dependency.
if ( ! $targetClass->subClasses) {
continue;
}
foreach ($targetClass->subClasses as $subClassName) {
$targetSubClass = $this->em->getClassMetadata($subClassName);
if ( ! $calc->hasClass($subClassName)) {
$calc->addClass($targetSubClass);
$newNodes[] = $targetSubClass;
2010-06-06 20:23:37 +04:00
}
$calc->addDependency($targetSubClass, $class);
}
}
}
2009-12-21 14:06:27 +03:00
return $calc->getCommitOrder();
}
/**
2009-07-19 20:54:53 +04:00
* Schedules an entity for insertion into the database.
* If the entity already has an identifier, it will be added to the identity map.
*
* @param object $entity The entity to schedule for insertion.
*
2012-12-01 20:28:06 +04:00
* @return void
*
* @throws ORMInvalidArgumentException
* @throws \InvalidArgumentException
*/
2009-07-19 20:54:53 +04:00
public function scheduleForInsert($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->entityUpdates[$oid])) {
throw new InvalidArgumentException("Dirty entity can not be scheduled for insertion.");
}
if (isset($this->entityDeletions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertForRemovedEntity($entity);
}
if (isset($this->originalEntityData[$oid]) && ! isset($this->entityInsertions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertForManagedEntity($entity);
}
if (isset($this->entityInsertions[$oid])) {
throw ORMInvalidArgumentException::scheduleInsertTwice($entity);
}
$this->entityInsertions[$oid] = $entity;
2009-12-18 15:30:19 +03:00
if (isset($this->entityIdentifiers[$oid])) {
$this->addToIdentityMap($entity);
}
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
}
/**
* Checks whether an entity is scheduled for insertion.
*
* @param object $entity
*
* @return boolean
*/
2009-07-19 20:54:53 +04:00
public function isScheduledForInsert($entity)
{
return isset($this->entityInsertions[spl_object_hash($entity)]);
}
/**
* Schedules an entity for being updated.
*
* @param object $entity The entity to schedule for being updated.
*
2012-12-01 20:28:06 +04:00
* @return void
*
* @throws ORMInvalidArgumentException
*/
2009-07-19 20:54:53 +04:00
public function scheduleForUpdate($entity)
{
$oid = spl_object_hash($entity);
if ( ! isset($this->entityIdentifiers[$oid])) {
throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "scheduling for update");
}
if (isset($this->entityDeletions[$oid])) {
throw ORMInvalidArgumentException::entityIsRemoved($entity, "schedule for update");
}
if ( ! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
$this->entityUpdates[$oid] = $entity;
}
}
/**
* INTERNAL:
* Schedules an extra update that will be executed immediately after the
* regular entity updates within the currently running commit cycle.
*
2009-11-15 14:42:05 +03:00
* Extra updates for entities are stored as (entity, changeset) tuples.
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param object $entity The entity for which to schedule an extra update.
* @param array $changeset The changeset of the entity (what to update).
*
* @return void
*/
public function scheduleExtraUpdate($entity, array $changeset)
{
$oid = spl_object_hash($entity);
$extraUpdate = array($entity, $changeset);
if (isset($this->extraUpdates[$oid])) {
list($ignored, $changeset2) = $this->extraUpdates[$oid];
$extraUpdate = array($entity, $changeset + $changeset2);
2009-11-15 14:42:05 +03:00
}
$this->extraUpdates[$oid] = $extraUpdate;
}
/**
* 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.
*
* @param object $entity
*
* @return boolean
*/
2009-07-19 20:54:53 +04:00
public function isScheduledForUpdate($entity)
{
return isset($this->entityUpdates[spl_object_hash($entity)]);
}
/**
* Checks whether an entity is registered to be checked in the unit of work.
*
* @param object $entity
*
* @return boolean
*/
2010-07-15 17:52:42 +04:00
public function isScheduledForDirtyCheck($entity)
{
$rootEntityName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
2010-07-15 17:52:42 +04:00
return isset($this->scheduledForDirtyCheck[$rootEntityName][spl_object_hash($entity)]);
}
/**
2010-02-24 22:19:04 +03:00
* INTERNAL:
* Schedules an entity for deletion.
*
2009-07-19 20:54:53 +04:00
* @param object $entity
2012-12-01 20:28:06 +04:00
*
* @return void
*/
2009-07-19 20:54:53 +04:00
public function scheduleForDelete($entity)
{
$oid = spl_object_hash($entity);
if (isset($this->entityInsertions[$oid])) {
if ($this->isInIdentityMap($entity)) {
$this->removeFromIdentityMap($entity);
}
unset($this->entityInsertions[$oid], $this->entityStates[$oid]);
return; // entity has not been persisted yet, so nothing more to do.
}
if ( ! $this->isInIdentityMap($entity)) {
return;
}
$this->removeFromIdentityMap($entity);
if (isset($this->entityUpdates[$oid])) {
unset($this->entityUpdates[$oid]);
2008-09-07 17:48:40 +04:00
}
if ( ! isset($this->entityDeletions[$oid])) {
$this->entityDeletions[$oid] = $entity;
$this->entityStates[$oid] = self::STATE_REMOVED;
}
}
/**
* Checks whether an entity is registered as removed/deleted with the unit
* of work.
*
* @param object $entity
*
* @return boolean
*/
2009-07-19 20:54:53 +04:00
public function isScheduledForDelete($entity)
{
return isset($this->entityDeletions[spl_object_hash($entity)]);
}
/**
2009-07-19 20:54:53 +04:00
* Checks whether an entity is scheduled for insertion, update or deletion.
*
2012-12-01 20:28:06 +04:00
* @param object $entity
*
2009-07-19 20:54:53 +04:00
* @return boolean
*/
2009-07-19 20:54:53 +04:00
public function isEntityScheduled($entity)
{
$oid = spl_object_hash($entity);
return isset($this->entityInsertions[$oid])
|| isset($this->entityUpdates[$oid])
|| isset($this->entityDeletions[$oid]);
}
/**
* INTERNAL:
* Registers an entity in the identity map.
* Note that entities in a hierarchy are registered with the class name of
* the root entity.
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param object $entity The entity to register.
*
2012-12-01 20:28:06 +04:00
* @return boolean TRUE if the registration was successful, FALSE if the identity of
* the entity in question is already managed.
*
2012-12-01 20:28:06 +04:00
* @throws ORMInvalidArgumentException
*/
public function addToIdentityMap($entity)
{
$classMetadata = $this->em->getClassMetadata(get_class($entity));
$idHash = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]);
if ($idHash === '') {
throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity);
}
$className = $classMetadata->rootEntityName;
if (isset($this->identityMap[$className][$idHash])) {
return false;
}
$this->identityMap[$className][$idHash] = $entity;
return true;
}
/**
2010-07-04 20:55:49 +04:00
* Gets the state of an entity with regard to the current unit of work.
*
2012-12-01 20:28:06 +04:00
* @param object $entity
* @param int|null $assume The state to assume if the state is not yet known (not MANAGED or REMOVED).
* This parameter can be set to improve performance of entity state detection
* by potentially avoiding a database lookup if the distinction between NEW and DETACHED
* is either known or does not matter for the caller of the method.
*
* @return int The entity state.
*/
public function getEntityState($entity, $assume = null)
{
$oid = spl_object_hash($entity);
if (isset($this->entityStates[$oid])) {
return $this->entityStates[$oid];
}
if ($assume !== null) {
return $assume;
}
// State can only be NEW or DETACHED, because MANAGED/REMOVED states are known.
// Note that you can not remember the NEW or DETACHED state in _entityStates since
// the UoW does not hold references to such objects and the object hash can be reused.
// More generally because the state may "change" between NEW/DETACHED without the UoW being aware of it.
$class = $this->em->getClassMetadata(get_class($entity));
$id = $class->getIdentifierValues($entity);
if ( ! $id) {
return self::STATE_NEW;
}
if ($class->containsForeignIdentifier) {
$id = $this->flattenIdentifier($class, $id);
}
switch (true) {
case ($class->isIdentifierNatural());
// Check for a version field, if available, to avoid a db lookup.
if ($class->isVersioned) {
return ($class->getFieldValue($entity, $class->versionField))
? self::STATE_DETACHED
: self::STATE_NEW;
}
// Last try before db lookup: check the identity map.
if ($this->tryGetById($id, $class->rootEntityName)) {
2010-07-04 20:55:49 +04:00
return self::STATE_DETACHED;
}
// db lookup
if ($this->getEntityPersister($class->name)->exists($entity)) {
return self::STATE_DETACHED;
}
return self::STATE_NEW;
case ( ! $class->idGenerator->isPostInsertGenerator()):
// if we have a pre insert generator we can't be sure that having an id
// really means that the entity exists. We have to verify this through
// the last resort: a db lookup
// Last try before db lookup: check the identity map.
if ($this->tryGetById($id, $class->rootEntityName)) {
return self::STATE_DETACHED;
}
// db lookup
if ($this->getEntityPersister($class->name)->exists($entity)) {
return self::STATE_DETACHED;
}
return self::STATE_NEW;
default:
return self::STATE_DETACHED;
2009-01-04 19:15:32 +03:00
}
}
2008-05-17 16:22:24 +04:00
/**
* INTERNAL:
2009-01-04 19:15:32 +03:00
* Removes an entity from the identity map. This effectively detaches the
* entity from the persistence management of Doctrine.
2008-05-17 16:22:24 +04:00
*
2009-10-07 16:39:46 +04:00
* @ignore
*
2012-12-01 20:28:06 +04:00
* @param object $entity
*
* @return boolean
2012-12-01 20:28:06 +04:00
*
* @throws ORMInvalidArgumentException
2008-05-17 16:22:24 +04:00
*/
public function removeFromIdentityMap($entity)
{
$oid = spl_object_hash($entity);
$classMetadata = $this->em->getClassMetadata(get_class($entity));
$idHash = implode(' ', $this->entityIdentifiers[$oid]);
if ($idHash === '') {
throw ORMInvalidArgumentException::entityHasNoIdentity($entity, "remove from identity map");
}
$className = $classMetadata->rootEntityName;
if (isset($this->identityMap[$className][$idHash])) {
unset($this->identityMap[$className][$idHash]);
unset($this->readOnlyObjects[$oid]);
//$this->entityStates[$oid] = self::STATE_DETACHED;
return true;
}
return false;
}
2008-05-17 16:22:24 +04:00
/**
* INTERNAL:
2009-01-04 19:15:32 +03:00
* Gets an entity in the identity map by its identifier hash.
2008-05-17 16:22:24 +04:00
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param string $idHash
* @param string $rootClassName
*
* @return object
2008-05-17 16:22:24 +04:00
*/
public function getByIdHash($idHash, $rootClassName)
{
return $this->identityMap[$rootClassName][$idHash];
}
/**
* INTERNAL:
* Tries to get an entity by its identifier hash. If no entity is found for
* the given hash, FALSE is returned.
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
2009-01-04 19:15:32 +03:00
* @param string $idHash
* @param string $rootClassName
*
2012-12-01 20:28:06 +04:00
* @return object|bool The found entity or FALSE.
*/
public function tryGetByIdHash($idHash, $rootClassName)
{
if (isset($this->identityMap[$rootClassName][$idHash])) {
return $this->identityMap[$rootClassName][$idHash];
}
return false;
}
/**
* Checks whether an entity is registered in the identity map of this UnitOfWork.
*
* @param object $entity
*
* @return boolean
*/
public function isInIdentityMap($entity)
{
$oid = spl_object_hash($entity);
if ( ! isset($this->entityIdentifiers[$oid])) {
return false;
}
$classMetadata = $this->em->getClassMetadata(get_class($entity));
$idHash = implode(' ', $this->entityIdentifiers[$oid]);
if ($idHash === '') {
return false;
}
return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]);
}
2008-05-17 16:22:24 +04:00
/**
* INTERNAL:
2008-05-17 16:22:24 +04:00
* Checks whether an identifier hash exists in the identity map.
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
2008-05-17 16:22:24 +04:00
* @param string $idHash
* @param string $rootClassName
*
2008-05-17 16:22:24 +04:00
* @return boolean
*/
public function containsIdHash($idHash, $rootClassName)
{
return isset($this->identityMap[$rootClassName][$idHash]);
}
/**
* Persists an entity as part of the current unit of work.
*
* @param object $entity The entity to persist.
2012-12-01 20:28:06 +04:00
*
* @return void
*/
2009-07-19 20:54:53 +04:00
public function persist($entity)
{
$visited = array();
$this->doPersist($entity, $visited);
}
/**
2010-07-04 20:55:49 +04:00
* Persists an entity as part of the current unit of work.
*
2010-07-04 20:55:49 +04:00
* This method is internally called during persist() cascades as it tracks
* the already visited entities to prevent infinite recursions.
*
2012-12-01 20:28:06 +04:00
* @param object $entity The entity to persist.
* @param array $visited The already visited entities.
*
* @return void
*
* @throws ORMInvalidArgumentException
* @throws UnexpectedValueException
*/
private function doPersist($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));
// We assume NEW, so DETACHED entities result in an exception on flush (constraint violation).
// If we would detect DETACHED here we would throw an exception anyway with the same
// consequences (not recoverable/programming error), so just assuming NEW here
// lets us avoid some database lookups for entities with natural identifiers.
$entityState = $this->getEntityState($entity, self::STATE_NEW);
2010-07-04 20:55:49 +04:00
switch ($entityState) {
case self::STATE_MANAGED:
// Nothing to do, except if policy is "deferred explicit"
if ($class->isChangeTrackingDeferredExplicit()) {
2009-01-29 20:00:44 +03:00
$this->scheduleForDirtyCheck($entity);
}
break;
case self::STATE_NEW:
2010-07-04 20:55:49 +04:00
$this->persistNew($class, $entity);
break;
case self::STATE_REMOVED:
// Entity becomes managed again
unset($this->entityDeletions[$oid]);
$this->entityStates[$oid] = self::STATE_MANAGED;
break;
case self::STATE_DETACHED:
// Can actually not happen right now since we assume STATE_NEW.
throw ORMInvalidArgumentException::detachedEntityCannot($entity, "persisted");
default:
throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
}
2010-07-04 20:55:49 +04:00
$this->cascadePersist($entity, $visited);
}
/**
* Deletes an entity as part of the current unit of work.
*
* @param object $entity The entity to remove.
2012-12-01 20:28:06 +04:00
*
* @return void
*/
2009-07-19 20:54:53 +04:00
public function remove($entity)
{
$visited = array();
$this->doRemove($entity, $visited);
}
2008-09-07 17:48:40 +04:00
/**
2009-01-29 20:00:44 +03:00
* Deletes an entity as part of the current unit of work.
*
2009-01-29 20:00:44 +03:00
* This method is internally called during delete() cascades as it tracks
* the already visited entities to prevent infinite recursions.
2008-09-07 17:48:40 +04:00
*
2012-12-01 20:28:06 +04:00
* @param object $entity The entity to delete.
* @param array $visited The map of the already visited entities.
*
* @return void
*
* @throws ORMInvalidArgumentException If the instance is a detached entity.
* @throws UnexpectedValueException
2008-09-07 17:48:40 +04:00
*/
private function doRemove($entity, array &$visited)
{
$oid = spl_object_hash($entity);
if (isset($visited[$oid])) {
return; // Prevent infinite recursion
}
$visited[$oid] = $entity; // mark visited
// Cascade first, because scheduleForDelete() removes the entity from the identity map, which
// can cause problems when a lazy proxy has to be initialized for the cascade operation.
$this->cascadeRemove($entity, $visited);
$class = $this->em->getClassMetadata(get_class($entity));
$entityState = $this->getEntityState($entity);
switch ($entityState) {
case self::STATE_NEW:
case self::STATE_REMOVED:
2009-01-29 20:00:44 +03:00
// nothing to do
break;
case self::STATE_MANAGED:
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::preRemove);
2012-07-31 05:26:55 +04:00
2012-11-10 00:14:51 +04:00
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::preRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
2009-07-18 22:06:30 +04:00
}
2009-07-19 20:54:53 +04:00
$this->scheduleForDelete($entity);
break;
case self::STATE_DETACHED:
throw ORMInvalidArgumentException::detachedEntityCannot($entity, "removed");
default:
throw new UnexpectedValueException("Unexpected entity state: $entityState." . self::objToStr($entity));
}
}
/**
* Merges the state of the given detached entity into this UnitOfWork.
*
* @param object $entity
*
2012-12-01 20:28:06 +04:00
* @return object The managed copy of the entity.
*
* @throws OptimisticLockException If the entity uses optimistic locking through a version
* attribute and the version check against the managed copy fails.
*
* @todo Require active transaction!? OptimisticLockException may result in undefined state!?
*/
public function merge($entity)
{
$visited = array();
return $this->doMerge($entity, $visited);
}
/**
* convert foreign identifiers into scalar foreign key values to avoid object to string conversion failures.
*
* @param ClassMetadata $class
* @param array $id
* @return array
*/
private function flattenIdentifier($class, $id)
{
$flatId = array();
foreach ($id as $idField => $idValue) {
if (isset($class->associationMappings[$idField])) {
$targetClassMetadata = $this->em->getClassMetadata($class->associationMappings[$idField]['targetEntity']);
$associatedId = $this->getEntityIdentifier($idValue);
$flatId[$idField] = $associatedId[$targetClassMetadata->identifier[0]];
2013-12-16 02:31:35 +04:00
} else {
$flatId[$idField] = $idValue;
}
}
return $flatId;
}
/**
* Executes a merge operation on an entity.
*
2012-12-01 20:28:06 +04:00
* @param object $entity
* @param array $visited
* @param object|null $prevManagedCopy
* @param array|null $assoc
*
* @return object The managed copy of the entity.
*
* @throws OptimisticLockException If the entity uses optimistic locking through a version
* attribute and the version check against the managed copy fails.
* @throws ORMInvalidArgumentException If the entity instance is NEW.
* @throws EntityNotFoundException
*/
private function doMerge($entity, array &$visited, $prevManagedCopy = null, $assoc = null)
{
2010-07-29 16:08:36 +04:00
$oid = spl_object_hash($entity);
2010-07-29 16:08:36 +04:00
if (isset($visited[$oid])) {
2012-07-04 23:55:48 +04:00
return $visited[$oid]; // Prevent infinite recursion
}
$visited[$oid] = $entity; // mark visited
$class = $this->em->getClassMetadata(get_class($entity));
2010-07-29 16:08:36 +04:00
// First we assume DETACHED, although it can still be NEW but we can avoid
// an extra db-roundtrip this way. If it is not MANAGED but has an identity,
// we need to fetch it from the db anyway in order to merge.
2010-07-29 16:08:36 +04:00
// MANAGED entities are ignored by the merge operation.
$managedCopy = $entity;
if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
2013-01-06 17:56:11 +04:00
if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
$this->em->getProxyFactory()->resetUninitializedProxy($entity);
$entity->__load();
}
// Try to look the entity up in the identity map.
2010-07-29 16:08:36 +04:00
$id = $class->getIdentifierValues($entity);
// If there is no ID, it is actually NEW.
if ( ! $id) {
$managedCopy = $this->newInstance($class);
2010-07-29 16:08:36 +04:00
$this->persistNew($class, $managedCopy);
} else {
$flatId = ($class->containsForeignIdentifier)
? $this->flattenIdentifier($class, $id)
: $id;
$managedCopy = $this->tryGetById($flatId, $class->rootEntityName);
2010-07-29 16:08:36 +04:00
if ($managedCopy) {
// We have the entity in-memory already, just make sure its not removed.
if ($this->getEntityState($managedCopy) == self::STATE_REMOVED) {
throw ORMInvalidArgumentException::entityIsRemoved($managedCopy, "merge");
2010-07-29 16:08:36 +04:00
}
} else {
// We need to fetch the managed copy in order to merge.
$managedCopy = $this->em->find($class->name, $flatId);
2010-07-29 16:08:36 +04:00
}
2010-04-10 02:00:36 +04:00
2010-07-29 16:08:36 +04:00
if ($managedCopy === null) {
// If the identifier is ASSIGNED, it is NEW, otherwise an error
// since the managed entity was not found.
if ( ! $class->isIdentifierNatural()) {
2010-07-29 16:08:36 +04:00
throw new EntityNotFoundException;
}
$managedCopy = $this->newInstance($class);
$class->setIdentifierValues($managedCopy, $id);
$this->persistNew($class, $managedCopy);
} else {
if ($managedCopy instanceof Proxy && ! $managedCopy->__isInitialized__) {
$managedCopy->__load();
}
2010-07-29 16:08:36 +04:00
}
}
2010-04-10 02:00:36 +04:00
if ($class->isVersioned) {
$reflField = $class->reflFields[$class->versionField];
$managedCopyVersion = $reflField->getValue($managedCopy);
$entityVersion = $reflField->getValue($entity);
2013-04-06 18:11:52 +04:00
// Throw exception if versions don't match.
if ($managedCopyVersion != $entityVersion) {
2013-03-11 04:08:58 +04:00
throw OptimisticLockException::lockFailedVersionMismatch($entity, $entityVersion, $managedCopyVersion);
}
}
2010-04-10 02:00:36 +04:00
// Merge state of $entity into existing (managed) entity
foreach ($class->reflClass->getProperties() as $prop) {
$name = $prop->name;
$prop->setAccessible(true);
if ( ! isset($class->associationMappings[$name])) {
if ( ! $class->isIdentifier($name)) {
$prop->setValue($managedCopy, $prop->getValue($entity));
}
} else {
$assoc2 = $class->associationMappings[$name];
if ($assoc2['type'] & ClassMetadata::TO_ONE) {
$other = $prop->getValue($entity);
if ($other === null) {
$prop->setValue($managedCopy, null);
} else if ($other instanceof Proxy && !$other->__isInitialized__) {
// do not merge fields marked lazy that have not been fetched.
continue;
} else if ( ! $assoc2['isCascadeMerge']) {
if ($this->getEntityState($other) === self::STATE_DETACHED) {
$targetClass = $this->em->getClassMetadata($assoc2['targetEntity']);
$relatedId = $targetClass->getIdentifierValues($other);
if ($targetClass->subClasses) {
$other = $this->em->find($targetClass->name, $relatedId);
} else {
$other = $this->em->getProxyFactory()->getProxy($assoc2['targetEntity'], $relatedId);
$this->registerManaged($other, $relatedId, array());
}
}
$prop->setValue($managedCopy, $other);
}
} else {
$mergeCol = $prop->getValue($entity);
if ($mergeCol instanceof PersistentCollection && !$mergeCol->isInitialized()) {
// do not merge fields marked lazy that have not been fetched.
// keep the lazy persistent collection of the managed copy.
continue;
}
$managedCol = $prop->getValue($managedCopy);
if (!$managedCol) {
$managedCol = new PersistentCollection($this->em,
$this->em->getClassMetadata($assoc2['targetEntity']),
new ArrayCollection
);
$managedCol->setOwner($managedCopy, $assoc2);
$prop->setValue($managedCopy, $managedCol);
$this->originalEntityData[$oid][$name] = $managedCol;
}
if ($assoc2['isCascadeMerge']) {
$managedCol->initialize();
// clear and set dirty a managed collection if its not also the same collection to merge from.
if (!$managedCol->isEmpty() && $managedCol !== $mergeCol) {
$managedCol->unwrap()->clear();
$managedCol->setDirty(true);
if ($assoc2['isOwningSide'] && $assoc2['type'] == ClassMetadata::MANY_TO_MANY && $class->isChangeTrackingNotify()) {
$this->scheduleForDirtyCheck($managedCopy);
}
}
}
}
}
if ($class->isChangeTrackingNotify()) {
2010-07-30 19:18:25 +04:00
// Just treat all properties as changed, there is no other choice.
$this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy));
}
}
2010-07-30 19:18:25 +04:00
if ($class->isChangeTrackingDeferredExplicit()) {
2010-07-29 16:08:36 +04:00
$this->scheduleForDirtyCheck($entity);
}
}
if ($prevManagedCopy !== null) {
$assocField = $assoc['fieldName'];
$prevClass = $this->em->getClassMetadata(get_class($prevManagedCopy));
if ($assoc['type'] & ClassMetadata::TO_ONE) {
$prevClass->reflFields[$assocField]->setValue($prevManagedCopy, $managedCopy);
} else {
$prevClass->reflFields[$assocField]->getValue($prevManagedCopy)->add($managedCopy);
if ($assoc['type'] == ClassMetadata::ONE_TO_MANY) {
$class->reflFields[$assoc['mappedBy']]->setValue($managedCopy, $prevManagedCopy);
}
}
}
// Mark the managed copy visited as well
$visited[spl_object_hash($managedCopy)] = true;
$this->cascadeMerge($entity, $managedCopy, $visited);
return $managedCopy;
}
/**
* Detaches an entity from the persistence management. It's persistence will
* no longer be managed by Doctrine.
*
* @param object $entity The entity to detach.
2012-12-01 20:28:06 +04:00
*
* @return void
*/
public function detach($entity)
{
$visited = array();
2011-12-01 19:00:26 +04:00
$this->doDetach($entity, $visited);
}
/**
* Executes a detach operation on the given entity.
*
2012-12-01 20:28:06 +04:00
* @param object $entity
* @param array $visited
* @param boolean $noCascade if true, don't cascade detach operation.
*
* @return void
*/
private function doDetach($entity, array &$visited, $noCascade = false)
{
$oid = spl_object_hash($entity);
2011-12-01 19:00:26 +04:00
if (isset($visited[$oid])) {
return; // Prevent infinite recursion
}
$visited[$oid] = $entity; // mark visited
switch ($this->getEntityState($entity, self::STATE_DETACHED)) {
case self::STATE_MANAGED:
if ($this->isInIdentityMap($entity)) {
$this->removeFromIdentityMap($entity);
}
2011-12-01 19:00:26 +04:00
unset(
2011-12-01 19:00:26 +04:00
$this->entityInsertions[$oid],
$this->entityUpdates[$oid],
2011-12-01 19:00:26 +04:00
$this->entityDeletions[$oid],
$this->entityIdentifiers[$oid],
2011-12-01 19:00:26 +04:00
$this->entityStates[$oid],
$this->originalEntityData[$oid]
);
break;
case self::STATE_NEW:
case self::STATE_DETACHED:
return;
}
if ( ! $noCascade) {
$this->cascadeDetach($entity, $visited);
}
}
2009-07-21 19:53:58 +04:00
/**
* Refreshes the state of the given entity from the database, overwriting
* any local, unpersisted changes.
*
* @param object $entity The entity to refresh.
*
2012-12-01 20:28:06 +04:00
* @return void
*
* @throws InvalidArgumentException If the entity is not MANAGED.
2009-07-21 19:53:58 +04:00
*/
public function refresh($entity)
{
$visited = array();
2011-12-01 19:00:26 +04:00
$this->doRefresh($entity, $visited);
2009-07-21 19:53:58 +04:00
}
2009-07-21 19:53:58 +04:00
/**
* Executes a refresh operation on an entity.
*
2012-12-01 20:28:06 +04:00
* @param object $entity The entity to refresh.
* @param array $visited The already visited entities during cascades.
*
* @return void
*
* @throws ORMInvalidArgumentException If the entity is not MANAGED.
2009-07-21 19:53:58 +04:00
*/
private function doRefresh($entity, array &$visited)
2009-07-21 19:53:58 +04:00
{
$oid = spl_object_hash($entity);
2011-12-01 19:00:26 +04:00
2009-07-21 19:53:58 +04:00
if (isset($visited[$oid])) {
return; // Prevent infinite recursion
}
$visited[$oid] = $entity; // mark visited
$class = $this->em->getClassMetadata(get_class($entity));
2011-12-01 19:00:26 +04:00
if ($this->getEntityState($entity) !== self::STATE_MANAGED) {
throw ORMInvalidArgumentException::entityNotManaged($entity);
2009-07-21 19:53:58 +04:00
}
2011-12-01 19:00:26 +04:00
$this->getEntityPersister($class->name)->refresh(
array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
$entity
);
$this->cascadeRefresh($entity, $visited);
2009-07-21 19:53:58 +04:00
}
2009-07-21 19:53:58 +04:00
/**
* Cascades a refresh operation to associated entities.
*
* @param object $entity
2012-12-01 20:28:06 +04:00
* @param array $visited
*
* @return void
2009-07-21 19:53:58 +04:00
*/
private function cascadeRefresh($entity, array &$visited)
2009-07-21 19:53:58 +04:00
{
$class = $this->em->getClassMetadata(get_class($entity));
2011-12-01 19:00:26 +04:00
$associationMappings = array_filter(
$class->associationMappings,
function ($assoc) { return $assoc['isCascadeRefresh']; }
);
foreach ($associationMappings as $assoc) {
$relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2011-12-01 19:00:26 +04:00
switch (true) {
case ($relatedEntities instanceof PersistentCollection):
2009-11-13 22:34:10 +03:00
// Unwrap so that foreach() does not initialize
$relatedEntities = $relatedEntities->unwrap();
// break; is commented intentionally!
2011-12-01 19:00:26 +04:00
case ($relatedEntities instanceof Collection):
case (is_array($relatedEntities)):
foreach ($relatedEntities as $relatedEntity) {
$this->doRefresh($relatedEntity, $visited);
}
break;
2011-12-01 19:00:26 +04:00
case ($relatedEntities !== null):
$this->doRefresh($relatedEntities, $visited);
break;
2011-12-01 19:00:26 +04:00
default:
// Do nothing
2009-07-21 19:53:58 +04:00
}
}
}
/**
* Cascades a detach operation to associated entities.
*
* @param object $entity
2012-12-01 20:28:06 +04:00
* @param array $visited
*
* @return void
*/
private function cascadeDetach($entity, array &$visited)
{
$class = $this->em->getClassMetadata(get_class($entity));
2011-12-01 19:00:26 +04:00
$associationMappings = array_filter(
$class->associationMappings,
function ($assoc) { return $assoc['isCascadeDetach']; }
);
foreach ($associationMappings as $assoc) {
$relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2011-12-01 19:00:26 +04:00
switch (true) {
case ($relatedEntities instanceof PersistentCollection):
// Unwrap so that foreach() does not initialize
$relatedEntities = $relatedEntities->unwrap();
// break; is commented intentionally!
2011-12-01 19:00:26 +04:00
case ($relatedEntities instanceof Collection):
case (is_array($relatedEntities)):
foreach ($relatedEntities as $relatedEntity) {
$this->doDetach($relatedEntity, $visited);
}
break;
2011-12-01 19:00:26 +04:00
case ($relatedEntities !== null):
$this->doDetach($relatedEntities, $visited);
break;
2011-12-01 19:00:26 +04:00
default:
// Do nothing
}
}
}
/**
* Cascades a merge operation to associated entities.
*
* @param object $entity
* @param object $managedCopy
2012-12-01 20:28:06 +04:00
* @param array $visited
*
* @return void
*/
private function cascadeMerge($entity, $managedCopy, array &$visited)
{
$class = $this->em->getClassMetadata(get_class($entity));
2011-12-01 19:00:26 +04:00
$associationMappings = array_filter(
$class->associationMappings,
function ($assoc) { return $assoc['isCascadeMerge']; }
);
foreach ($associationMappings as $assoc) {
$relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2011-12-01 19:00:26 +04:00
if ($relatedEntities instanceof Collection) {
if ($relatedEntities === $class->reflFields[$assoc['fieldName']]->getValue($managedCopy)) {
continue;
}
if ($relatedEntities instanceof PersistentCollection) {
// Unwrap so that foreach() does not initialize
$relatedEntities = $relatedEntities->unwrap();
}
2011-12-01 19:00:26 +04:00
foreach ($relatedEntities as $relatedEntity) {
$this->doMerge($relatedEntity, $visited, $managedCopy, $assoc);
}
} else if ($relatedEntities !== null) {
$this->doMerge($relatedEntities, $visited, $managedCopy, $assoc);
}
}
}
/**
* Cascades the save operation to associated entities.
*
2009-01-29 20:00:44 +03:00
* @param object $entity
2012-12-01 20:28:06 +04:00
* @param array $visited
*
* @return void
*/
private function cascadePersist($entity, array &$visited)
{
$class = $this->em->getClassMetadata(get_class($entity));
2011-12-01 19:00:26 +04:00
$associationMappings = array_filter(
$class->associationMappings,
function ($assoc) { return $assoc['isCascadePersist']; }
);
foreach ($associationMappings as $assoc) {
$relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
2011-12-01 19:00:26 +04:00
switch (true) {
case ($relatedEntities instanceof PersistentCollection):
// Unwrap so that foreach() does not initialize
$relatedEntities = $relatedEntities->unwrap();
// break; is commented intentionally!
2011-12-01 19:00:26 +04:00
case ($relatedEntities instanceof Collection):
case (is_array($relatedEntities)):
foreach ($relatedEntities as $relatedEntity) {
$this->doPersist($relatedEntity, $visited);
}
break;
2011-12-01 19:00:26 +04:00
case ($relatedEntities !== null):
$this->doPersist($relatedEntities, $visited);
break;
2011-12-01 19:00:26 +04:00
default:
// Do nothing
}
}
}
2009-01-04 19:15:32 +03:00
/**
* Cascades the delete operation to associated entities.
*
2009-01-29 20:00:44 +03:00
* @param object $entity
2012-12-01 20:28:06 +04:00
* @param array $visited
*
* @return void
2009-01-04 19:15:32 +03:00
*/
private function cascadeRemove($entity, array &$visited)
{
$class = $this->em->getClassMetadata(get_class($entity));
2011-12-01 19:00:26 +04:00
$associationMappings = array_filter(
$class->associationMappings,
function ($assoc) { return $assoc['isCascadeRemove']; }
);
2011-12-01 19:00:26 +04:00
foreach ($associationMappings as $assoc) {
2011-06-05 12:02:57 +04:00
if ($entity instanceof Proxy && !$entity->__isInitialized__) {
$entity->__load();
}
$relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);
switch (true) {
case ($relatedEntities instanceof Collection):
case (is_array($relatedEntities)):
// If its a PersistentCollection initialization is intended! No unwrap!
foreach ($relatedEntities as $relatedEntity) {
$this->doRemove($relatedEntity, $visited);
}
break;
2011-12-01 19:00:26 +04:00
case ($relatedEntities !== null):
$this->doRemove($relatedEntities, $visited);
break;
2011-12-01 19:00:26 +04:00
default:
// Do nothing
2009-01-04 19:15:32 +03:00
}
}
}
2009-01-04 19:15:32 +03:00
/**
* Acquire a lock on the given entity.
*
* @param object $entity
2012-12-01 20:28:06 +04:00
* @param int $lockMode
* @param int $lockVersion
*
* @return void
*
* @throws ORMInvalidArgumentException
* @throws TransactionRequiredException
* @throws OptimisticLockException
*/
public function lock($entity, $lockMode, $lockVersion = null)
{
if ($entity === null) {
throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock().");
}
if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) {
throw ORMInvalidArgumentException::entityNotManaged($entity);
}
$class = $this->em->getClassMetadata(get_class($entity));
switch ($lockMode) {
case \Doctrine\DBAL\LockMode::OPTIMISTIC;
if ( ! $class->isVersioned) {
throw OptimisticLockException::notVersioned($class->name);
}
if ($lockVersion === null) {
return;
}
2011-12-01 19:00:26 +04:00
$entityVersion = $class->reflFields[$class->versionField]->getValue($entity);
2011-12-01 19:00:26 +04:00
if ($entityVersion != $lockVersion) {
2013-03-11 04:08:58 +04:00
throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
}
2011-12-01 19:00:26 +04:00
break;
2011-12-01 19:00:26 +04:00
case \Doctrine\DBAL\LockMode::PESSIMISTIC_READ:
case \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE:
if (!$this->em->getConnection()->isTransactionActive()) {
throw TransactionRequiredException::transactionRequired();
}
$oid = spl_object_hash($entity);
$this->getEntityPersister($class->name)->lock(
array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
$lockMode
);
break;
2011-12-01 19:00:26 +04:00
default:
// Do nothing
}
}
2009-01-04 19:15:32 +03:00
/**
* Gets the CommitOrderCalculator used by the UnitOfWork to order commits.
*
* @return \Doctrine\ORM\Internal\CommitOrderCalculator
2009-01-04 19:15:32 +03:00
*/
public function getCommitOrderCalculator()
{
if ($this->commitOrderCalculator === null) {
$this->commitOrderCalculator = new Internal\CommitOrderCalculator;
2009-12-21 14:06:27 +03:00
}
2011-12-04 11:14:47 +04:00
return $this->commitOrderCalculator;
}
2009-01-04 19:15:32 +03:00
/**
* Clears the UnitOfWork.
*
2012-12-01 20:28:06 +04:00
* @param string|null $entityName if given, only entities of this type will get detached.
*
* @return void
2009-01-04 19:15:32 +03:00
*/
public function clear($entityName = null)
{
if ($entityName === null) {
$this->identityMap =
$this->entityIdentifiers =
$this->originalEntityData =
$this->entityChangeSets =
$this->entityStates =
$this->scheduledForDirtyCheck =
$this->entityInsertions =
$this->entityUpdates =
$this->entityDeletions =
$this->collectionDeletions =
$this->collectionUpdates =
$this->extraUpdates =
$this->readOnlyObjects =
$this->visitedCollections =
$this->orphanRemovals = array();
if ($this->commitOrderCalculator !== null) {
$this->commitOrderCalculator->clear();
}
} else {
$visited = array();
foreach ($this->identityMap as $className => $entities) {
if ($className === $entityName) {
foreach ($entities as $entity) {
$this->doDetach($entity, $visited, true);
}
}
}
2009-12-21 14:06:27 +03:00
}
2011-03-22 06:17:08 +03:00
if ($this->evm->hasListeners(Events::onClear)) {
$this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->em, $entityName));
2011-03-22 06:17:08 +03:00
}
}
/**
* 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.
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param object $entity
2012-12-01 20:28:06 +04:00
*
* @return void
*/
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
2012-12-01 20:28:06 +04:00
*
* @return void
*/
public function scheduleCollectionDeletion(PersistentCollection $coll)
2008-08-16 23:40:59 +04:00
{
$coid = spl_object_hash($coll);
2013-09-22 04:12:30 +04:00
// TODO: if $coll is already scheduled for recreation ... what to do?
2008-08-16 23:40:59 +04:00
// Just remove $coll from the scheduled recreations?
if (isset($this->collectionUpdates[$coid])) {
unset($this->collectionUpdates[$coid]);
}
$this->collectionDeletions[$coid] = $coll;
2008-08-16 23:40:59 +04:00
}
/**
* @param PersistentCollection $coll
*
* @return bool
*/
public function isCollectionScheduledForDeletion(PersistentCollection $coll)
2008-08-16 23:40:59 +04:00
{
return isset($this->collectionDeletions[spl_object_hash($coll)]);
2008-08-16 23:40:59 +04:00
}
/**
* @param ClassMetadata $class
*
* @return \Doctrine\Common\Persistence\ObjectManagerAware|object
*/
private function newInstance($class)
{
$entity = $class->newInstance();
2011-12-01 19:00:26 +04:00
if ($entity instanceof \Doctrine\Common\Persistence\ObjectManagerAware) {
$entity->injectObjectManager($this->em, $class);
}
2011-12-01 19:00:26 +04:00
return $entity;
}
/**
* INTERNAL:
2010-08-08 15:10:53 +04:00
* Creates an entity. Used for reconstitution of persistent entities.
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param string $className The name of the entity class.
2012-12-01 20:28:06 +04:00
* @param array $data The data for the entity.
* @param array $hints Any hints to account for during reconstitution/lookup of the entity.
*
2010-08-08 15:10:53 +04:00
* @return object The managed entity instance.
2012-12-01 20:28:06 +04:00
*
2009-10-09 18:27:35 +04:00
* @internal Highly performance-sensitive method.
*
* @todo Rename: getOrCreateEntity
*/
public function createEntity($className, array $data, &$hints = array())
{
$class = $this->em->getClassMetadata($className);
//$isReadOnly = isset($hints[Query::HINT_READ_ONLY]);
if ($class->isIdentifierComposite) {
$id = array();
2011-12-01 19:00:26 +04:00
foreach ($class->identifier as $fieldName) {
2011-12-01 19:00:26 +04:00
$id[$fieldName] = isset($class->associationMappings[$fieldName])
? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]
: $data[$fieldName];
}
2011-12-01 19:00:26 +04:00
$idHash = implode(' ', $id);
} else {
2011-12-01 19:00:26 +04:00
$idHash = isset($class->associationMappings[$class->identifier[0]])
? $data[$class->associationMappings[$class->identifier[0]]['joinColumns'][0]['name']]
: $data[$class->identifier[0]];
$id = array($class->identifier[0] => $idHash);
}
if (isset($this->identityMap[$class->rootEntityName][$idHash])) {
$entity = $this->identityMap[$class->rootEntityName][$idHash];
$oid = spl_object_hash($entity);
2011-12-01 19:00:26 +04:00
if (
isset($hints[Query::HINT_REFRESH])
&& isset($hints[Query::HINT_REFRESH_ENTITY])
&& ($unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY]) !== $entity
&& $unmanagedProxy instanceof Proxy
2013-02-21 05:20:11 +04:00
&& (($unmanagedProxyClass = $this->em->getClassMetadata(get_class($unmanagedProxy))) === $class)
) {
// DDC-1238 - we have a managed instance, but it isn't the provided one.
// Therefore we clear its identifier. Also, we must re-fetch metadata since the
// refreshed object may be anything
2013-02-21 05:20:11 +04:00
foreach ($unmanagedProxyClass->identifier as $fieldName) {
$unmanagedProxyClass->reflFields[$fieldName]->setValue($unmanagedProxy, null);
}
return $unmanagedProxy;
}
if ($entity instanceof Proxy && ! $entity->__isInitialized()) {
$entity->__setInitialized(true);
$overrideLocalValues = true;
2011-12-01 19:00:26 +04:00
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
// inject ObjectManager into just loaded proxies.
if ($overrideLocalValues && $entity instanceof ObjectManagerAware) {
$entity->injectObjectManager($this->em, $class);
}
} else {
$overrideLocalValues = isset($hints[Query::HINT_REFRESH]);
2011-11-10 19:16:55 +04:00
// If only a specific entity is set to refresh, check that it's the one
2013-10-08 02:53:32 +04:00
if (isset($hints[Query::HINT_REFRESH_ENTITY])) {
$overrideLocalValues = $hints[Query::HINT_REFRESH_ENTITY] === $entity;
}
// inject ObjectManager upon refresh.
if ($overrideLocalValues && $entity instanceof ObjectManagerAware) {
$entity->injectObjectManager($this->em, $class);
}
}
if ($overrideLocalValues) {
$this->originalEntityData[$oid] = $data;
}
} else {
$entity = $this->newInstance($class);
$oid = spl_object_hash($entity);
2011-12-01 19:00:26 +04:00
$this->entityIdentifiers[$oid] = $id;
$this->entityStates[$oid] = self::STATE_MANAGED;
$this->originalEntityData[$oid] = $data;
$this->identityMap[$class->rootEntityName][$idHash] = $entity;
2011-12-01 19:00:26 +04:00
2009-10-07 16:39:46 +04:00
if ($entity instanceof NotifyPropertyChanged) {
$entity->addPropertyChangedListener($this);
}
$overrideLocalValues = true;
}
if ( ! $overrideLocalValues) {
return $entity;
}
2011-12-01 19:00:26 +04:00
foreach ($data as $field => $value) {
if (isset($class->fieldMappings[$field])) {
$class->reflFields[$field]->setValue($entity, $value);
}
}
// Loading the entity right here, if its in the eager loading map get rid of it there.
unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]);
if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && ! $this->eagerLoadingEntities[$class->rootEntityName]) {
unset($this->eagerLoadingEntities[$class->rootEntityName]);
}
// Properly initialize any unfetched associations, if partial objects are not allowed.
if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) {
return $entity;
}
2011-12-01 19:00:26 +04:00
foreach ($class->associationMappings as $field => $assoc) {
// Check if the association is not among the fetch-joined associations already.
if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) {
continue;
}
$targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
switch (true) {
case ($assoc['type'] & ClassMetadata::TO_ONE):
if ( ! $assoc['isOwningSide']) {
// Inverse side of x-to-one can never be lazy
$class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity));
continue 2;
}
2010-01-30 00:24:29 +03:00
2013-02-14 02:42:13 +04:00
// use the entity association
if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) {
$class->reflFields[$field]->setValue($entity, $data[$field]);
$this->originalEntityData[$oid][$field] = $data[$field];
continue;
}
$associatedId = array();
// TODO: Is this even computed right in all cases of composite keys?
foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
$joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;
if ($joinColumnValue !== null) {
if ($targetClass->containsForeignIdentifier) {
$associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue;
} else {
$associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
}
}
}
if ( ! $associatedId) {
// Foreign key is NULL
$class->reflFields[$field]->setValue($entity, null);
$this->originalEntityData[$oid][$field] = null;
continue;
}
if ( ! isset($hints['fetchMode'][$class->name][$field])) {
$hints['fetchMode'][$class->name][$field] = $assoc['fetch'];
}
// Foreign key is set
// 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);
switch (true) {
case (isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash])):
$newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash];
2012-01-19 08:09:23 +04:00
// If this is an uninitialized proxy, we are deferring eager loads,
// this association is marked as eager fetch, and its an uninitialized proxy (wtf!)
2012-01-19 08:09:23 +04:00
// then we can append this entity for eager loading!
if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER &&
2013-04-08 13:27:22 +04:00
isset($hints[self::HINT_DEFEREAGERLOAD]) &&
!$targetClass->isIdentifierComposite &&
$newValue instanceof Proxy &&
$newValue->__isInitialized__ === false) {
$this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
}
break;
case ($targetClass->subClasses):
// If it might be a subtype, it can not be lazy. There isn't even
// a way to solve this with deferred eager loading, which means putting
// an entity with subclasses at a *-to-one location is really bad! (performance-wise)
$newValue = $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, $associatedId);
break;
default:
switch (true) {
// We are negating the condition here. Other cases will assume it is valid!
case ($hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER):
$newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
break;
// Deferred eager load only works for single identifier classes
2013-04-08 13:27:22 +04:00
case (isset($hints[self::HINT_DEFEREAGERLOAD]) && ! $targetClass->isIdentifierComposite):
// TODO: Is there a faster approach?
$this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId);
$newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId);
break;
default:
// TODO: This is very imperformant, ignore it?
$newValue = $this->em->find($assoc['targetEntity'], $associatedId);
break;
}
// PERF: Inlined & optimized code from UnitOfWork#registerManaged()
$newValueOid = spl_object_hash($newValue);
$this->entityIdentifiers[$newValueOid] = $associatedId;
$this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue;
if (
$newValue instanceof NotifyPropertyChanged &&
( ! $newValue instanceof Proxy || $newValue->__isInitialized())
) {
$newValue->addPropertyChangedListener($this);
}
$this->entityStates[$newValueOid] = self::STATE_MANAGED;
// make sure that when an proxy is then finally loaded, $this->originalEntityData is set also!
break;
}
$this->originalEntityData[$oid][$field] = $newValue;
$class->reflFields[$field]->setValue($entity, $newValue);
if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) {
$inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']];
$targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity);
}
break;
default:
2013-02-14 02:42:13 +04:00
// Ignore if its a cached collection
if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity, $field) instanceof PersistentCollection) {
break;
}
// use the given collection
if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) {
$data[$field]->setOwner($entity, $assoc);
$class->reflFields[$field]->setValue($entity, $data[$field]);
$this->originalEntityData[$oid][$field] = $data[$field];
break;
}
// Inject collection
$pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection);
$pColl->setOwner($entity, $assoc);
$pColl->setInitialized(false);
$reflField = $class->reflFields[$field];
$reflField->setValue($entity, $pColl);
if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) {
$this->loadCollection($pColl);
$pColl->takeSnapshot();
}
$this->originalEntityData[$oid][$field] = $pColl;
break;
}
}
if ($overrideLocalValues) {
$invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postLoad);
2012-11-10 00:14:51 +04:00
if ($invoke !== ListenersInvoker::INVOKE_NONE) {
$this->listenersInvoker->invoke($class, Events::postLoad, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
}
}
return $entity;
}
/**
* @return void
*/
public function triggerEagerLoads()
{
if ( ! $this->eagerLoadingEntities) {
return;
}
// avoid infinite recursion
$eagerLoadingEntities = $this->eagerLoadingEntities;
$this->eagerLoadingEntities = array();
foreach ($eagerLoadingEntities as $entityName => $ids) {
2012-01-19 08:27:28 +04:00
if ( ! $ids) {
continue;
}
2012-01-19 08:09:23 +04:00
$class = $this->em->getClassMetadata($entityName);
2012-01-19 08:09:23 +04:00
$this->getEntityPersister($entityName)->loadAll(
array_combine($class->identifier, array(array_values($ids)))
);
}
}
/**
* Initializes (loads) an uninitialized persistent collection of an entity.
*
* @param \Doctrine\ORM\PersistentCollection $collection The collection to initialize.
*
* @return void
2012-12-01 20:28:06 +04:00
*
* @todo Maybe later move to EntityManager#initialize($proxyOrCollection). See DDC-733.
*/
public function loadCollection(PersistentCollection $collection)
{
$assoc = $collection->getMapping();
$persister = $this->getEntityPersister($assoc['targetEntity']);
switch ($assoc['type']) {
case ClassMetadata::ONE_TO_MANY:
$persister->loadOneToManyCollection($assoc, $collection->getOwner(), $collection);
break;
case ClassMetadata::MANY_TO_MANY:
$persister->loadManyToManyCollection($assoc, $collection->getOwner(), $collection);
break;
}
$collection->setInitialized(true);
}
/**
* Gets the identity map of the UnitOfWork.
*
* @return array
*/
public function getIdentityMap()
{
return $this->identityMap;
}
/**
* 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();
}
/**
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param object $entity
* @param array $data
*
* @return void
*/
public function setOriginalEntityData($entity, array $data)
{
$this->originalEntityData[spl_object_hash($entity)] = $data;
}
/**
* INTERNAL:
* Sets a property value of the original data array of an entity.
*
2009-10-07 16:39:46 +04:00
* @ignore
2012-12-01 20:28:06 +04:00
*
* @param string $oid
* @param string $property
2012-12-01 20:28:06 +04:00
* @param mixed $value
*
* @return void
*/
public function setOriginalEntityProperty($oid, $property, $value)
{
$this->originalEntityData[$oid][$property] = $value;
}
/**
* Gets the identifier of an entity.
* The returned value is always an array of identifier values. If the entity
* has a composite identifier then the identifier values are in the same
* order as the identifier field names as returned by ClassMetadata#getIdentifierFieldNames().
*
* @param object $entity
*
* @return array The identifier values.
*/
public function getEntityIdentifier($entity)
{
return $this->entityIdentifiers[spl_object_hash($entity)];
}
2012-10-20 06:18:01 +04:00
/**
* Processes an entity instance to extract their identifier values.
2012-10-20 06:18:01 +04:00
*
* @param object $entity The entity instance.
*
* @return mixed A scalar value.
2012-10-20 06:18:01 +04:00
*
* @throws \Doctrine\ORM\ORMInvalidArgumentException
*/
public function getSingleIdentifierValue($entity)
{
$class = $this->em->getClassMetadata(get_class($entity));
if ($class->isIdentifierComposite) {
throw ORMInvalidArgumentException::invalidCompositeIdentifier();
}
$values = $this->isInIdentityMap($entity)
2012-10-20 06:18:01 +04:00
? $this->getEntityIdentifier($entity)
: $class->getIdentifierValues($entity);
return isset($values[$class->identifier[0]]) ? $values[$class->identifier[0]] : null;
}
/**
* Tries to find an entity with the given identifier in the identity map of
* this UnitOfWork.
*
2012-12-01 20:28:06 +04:00
* @param mixed $id The entity identifier to look for.
* @param string $rootClassName The name of the root class of the mapped entity hierarchy.
*
* @return object|bool Returns the entity with the specified identifier if it exists in
* this UnitOfWork, FALSE otherwise.
*/
public function tryGetById($id, $rootClassName)
{
$idHash = implode(' ', (array) $id);
if (isset($this->identityMap[$rootClassName][$idHash])) {
return $this->identityMap[$rootClassName][$idHash];
}
return false;
}
/**
* Schedules an entity for dirty-checking at commit-time.
*
* @param object $entity The entity to schedule for dirty-checking.
2012-12-01 20:28:06 +04:00
*
* @return void
*
* @todo Rename: scheduleForSynchronization
*/
2009-01-29 20:00:44 +03:00
public function scheduleForDirtyCheck($entity)
{
$rootClassName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
2010-07-15 17:52:42 +04:00
$this->scheduledForDirtyCheck[$rootClassName][spl_object_hash($entity)] = $entity;
2009-01-29 20:00:44 +03:00
}
/**
* 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);
}
/**
* Calculates the size of the UnitOfWork. The size of the UnitOfWork is the
* number of entities in the identity map.
2009-01-29 20:00:44 +03:00
*
* @return integer
*/
public function size()
{
$countArray = array_map(function ($item) { return count($item); }, $this->identityMap);
return array_sum($countArray);
}
/**
* Gets the EntityPersister for an Entity.
*
2012-12-01 20:28:06 +04:00
* @param string $entityName The name of the Entity.
*
2013-02-14 02:42:13 +04:00
* @return \Doctrine\ORM\Persisters\EntityPersister
*/
public function getEntityPersister($entityName)
{
if (isset($this->persisters[$entityName])) {
return $this->persisters[$entityName];
}
$class = $this->em->getClassMetadata($entityName);
switch (true) {
case ($class->isInheritanceTypeNone()):
2013-02-14 02:42:13 +04:00
$persister = new BasicEntityPersister($this->em, $class);
break;
case ($class->isInheritanceTypeSingleTable()):
2013-02-14 02:42:13 +04:00
$persister = new SingleTablePersister($this->em, $class);
break;
case ($class->isInheritanceTypeJoined()):
2013-02-14 02:42:13 +04:00
$persister = new JoinedSubclassPersister($this->em, $class);
break;
default:
2013-09-12 00:43:25 +04:00
throw new \RuntimeException('No persister found for entity.');
}
2013-02-14 02:42:13 +04:00
if ($this->hasCache && $class->cache !== null) {
$persister = $this->em->getConfiguration()
2013-10-03 21:55:55 +04:00
->getSecondLevelCacheConfiguration()
->getCacheFactory()
2013-02-14 02:42:13 +04:00
->buildCachedEntityPersister($this->em, $persister, $class);
}
$this->persisters[$entityName] = $persister;
return $this->persisters[$entityName];
}
/**
* Gets a collection persister for a collection-valued association.
*
* @param array $association
*
2013-02-14 02:42:13 +04:00
* @return \Doctrine\ORM\Persisters\CollectionPersister
*/
public function getCollectionPersister(array $association)
{
2013-02-14 02:42:13 +04:00
$role = isset($association['cache'])
? $association['sourceEntity'] . '::' . $association['fieldName']
: $association['type'];
2013-02-14 02:42:13 +04:00
if (isset($this->collectionPersisters[$role])) {
return $this->collectionPersisters[$role];
}
2013-02-14 02:42:13 +04:00
$persister = ClassMetadata::ONE_TO_MANY === $association['type']
? new OneToManyPersister($this->em)
: new ManyToManyPersister($this->em);
2013-02-14 02:42:13 +04:00
if ($this->hasCache && isset($association['cache'])) {
$persister = $this->em->getConfiguration()
2013-10-03 21:55:55 +04:00
->getSecondLevelCacheConfiguration()
->getCacheFactory()
2013-02-14 02:42:13 +04:00
->buildCachedCollectionPersister($this->em, $persister, $association);
}
2013-02-14 02:42:13 +04:00
$this->collectionPersisters[$role] = $persister;
2013-02-14 02:42:13 +04:00
return $this->collectionPersisters[$role];
}
/**
* INTERNAL:
* Registers an entity as managed.
*
* @param object $entity The entity.
2012-12-01 20:28:06 +04:00
* @param array $id The identifier values.
* @param array $data The original entity data.
*
* @return void
*/
2009-10-07 16:39:46 +04:00
public function registerManaged($entity, array $id, array $data)
{
$oid = spl_object_hash($entity);
$this->entityIdentifiers[$oid] = $id;
$this->entityStates[$oid] = self::STATE_MANAGED;
$this->originalEntityData[$oid] = $data;
$this->addToIdentityMap($entity);
if ($entity instanceof NotifyPropertyChanged && ( ! $entity instanceof Proxy || $entity->__isInitialized())) {
$entity->addPropertyChangedListener($this);
}
}
/**
* INTERNAL:
* Clears the property changeset of the entity with the given OID.
*
* @param string $oid The entity's OID.
2012-12-01 20:28:06 +04:00
*
* @return void
*/
public function clearEntityChangeSet($oid)
{
$this->entityChangeSets[$oid] = array();
}
/* PropertyChangedListener implementation */
/**
* Notifies this UnitOfWork of a property change in an entity.
*
2012-12-01 20:28:06 +04:00
* @param object $entity The entity that owns the property.
* @param string $propertyName The name of the property that changed.
2012-12-01 20:28:06 +04:00
* @param mixed $oldValue The old value of the property.
* @param mixed $newValue The new value of the property.
*
* @return void
*/
public function propertyChanged($entity, $propertyName, $oldValue, $newValue)
{
$oid = spl_object_hash($entity);
$class = $this->em->getClassMetadata(get_class($entity));
2010-05-01 14:14:16 +04:00
$isAssocField = isset($class->associationMappings[$propertyName]);
if ( ! $isAssocField && ! isset($class->fieldMappings[$propertyName])) {
return; // ignore non-persistent fields
}
2010-07-15 17:52:42 +04:00
// Update changeset and mark entity for synchronization
$this->entityChangeSets[$oid][$propertyName] = array($oldValue, $newValue);
2010-07-15 17:52:42 +04:00
if ( ! isset($this->scheduledForDirtyCheck[$class->rootEntityName][$oid])) {
$this->scheduleForDirtyCheck($entity);
}
}
2010-07-15 17:52:42 +04:00
2010-02-24 22:19:04 +03:00
/**
* Gets the currently scheduled entity insertions in this UnitOfWork.
*
2010-02-24 22:19:04 +03:00
* @return array
*/
public function getScheduledEntityInsertions()
{
return $this->entityInsertions;
2010-02-24 22:19:04 +03:00
}
2010-02-24 22:19:04 +03:00
/**
* Gets the currently scheduled entity updates in this UnitOfWork.
*
2010-02-24 22:19:04 +03:00
* @return array
*/
public function getScheduledEntityUpdates()
{
return $this->entityUpdates;
2010-02-24 22:19:04 +03:00
}
2010-02-24 22:19:04 +03:00
/**
* Gets the currently scheduled entity deletions in this UnitOfWork.
*
2010-02-24 22:19:04 +03:00
* @return array
*/
public function getScheduledEntityDeletions()
{
return $this->entityDeletions;
2010-02-24 22:19:04 +03:00
}
/**
* Gets the currently scheduled complete collection deletions
*
* @return array
*/
public function getScheduledCollectionDeletions()
{
return $this->collectionDeletions;
}
/**
* Gets the currently scheduled collection inserts, updates and deletes.
*
* @return array
*/
public function getScheduledCollectionUpdates()
{
return $this->collectionUpdates;
2010-07-04 20:55:49 +04:00
}
/**
* Helper method to initialize a lazy loading proxy or persistent collection.
*
2012-12-01 20:28:06 +04:00
* @param object $obj
*
* @return void
*/
public function initializeObject($obj)
{
if ($obj instanceof Proxy) {
$obj->__load();
return;
}
if ($obj instanceof PersistentCollection) {
$obj->initialize();
}
}
/**
* Helper method to show an object as string.
*
2012-12-01 20:28:06 +04:00
* @param object $obj
*
* @return string
*/
private static function objToStr($obj)
2010-07-04 20:55:49 +04:00
{
return method_exists($obj, '__toString') ? (string)$obj : get_class($obj).'@'.spl_object_hash($obj);
2010-07-04 20:55:49 +04:00
}
/**
* Marks an entity as read-only so that it will not be considered for updates during UnitOfWork#commit().
*
* This operation cannot be undone as some parts of the UnitOfWork now keep gathering information
* on this object that might be necessary to perform a correct update.
*
* @param object $object
*
* @return void
2012-12-01 20:28:06 +04:00
*
* @throws ORMInvalidArgumentException
*/
public function markReadOnly($object)
{
if ( ! is_object($object) || ! $this->isInIdentityMap($object)) {
throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
}
$this->readOnlyObjects[spl_object_hash($object)] = true;
}
/**
* Is this entity read only?
*
* @param object $object
*
* @return bool
2012-12-01 20:28:06 +04:00
*
* @throws ORMInvalidArgumentException
*/
public function isReadOnly($object)
{
2012-01-19 08:09:23 +04:00
if ( ! is_object($object)) {
throw ORMInvalidArgumentException::readOnlyRequiresManagedEntity($object);
}
2011-10-15 18:03:50 +04:00
return isset($this->readOnlyObjects[spl_object_hash($object)]);
}
2012-07-23 03:14:02 +04:00
2013-02-14 02:42:13 +04:00
/**
* Perform whatever processing is encapsulated here after completion of the transaction.
*/
private function afterTransactionComplete()
{
if ( ! $this->hasCache) {
return;
}
foreach ($this->persisters as $persister) {
2013-10-08 02:53:32 +04:00
if ($persister instanceof CachedPersister) {
2013-02-14 02:42:13 +04:00
$persister->afterTransactionComplete();
}
}
foreach ($this->collectionPersisters as $persister) {
2013-10-08 02:53:32 +04:00
if ($persister instanceof CachedPersister) {
2013-02-14 02:42:13 +04:00
$persister->afterTransactionComplete();
}
}
}
/**
* Perform whatever processing is encapsulated here after completion of the rolled-back.
*/
private function afterTransactionRolledBack()
{
if ( ! $this->hasCache) {
return;
}
foreach ($this->persisters as $persister) {
2013-10-08 02:53:32 +04:00
if ($persister instanceof CachedPersister) {
2013-02-14 02:42:13 +04:00
$persister->afterTransactionRolledBack();
}
}
foreach ($this->collectionPersisters as $persister) {
2013-10-08 02:53:32 +04:00
if ($persister instanceof CachedPersister) {
2013-02-14 02:42:13 +04:00
$persister->afterTransactionRolledBack();
}
}
}
2012-07-23 03:14:02 +04:00
private function dispatchOnFlushEvent()
{
if ($this->evm->hasListeners(Events::onFlush)) {
2012-07-31 05:26:55 +04:00
$this->evm->dispatchEvent(Events::onFlush, new OnFlushEventArgs($this->em));
2012-07-23 03:14:02 +04:00
}
}
private function dispatchPostFlushEvent()
{
if ($this->evm->hasListeners(Events::postFlush)) {
2012-07-31 05:26:55 +04:00
$this->evm->dispatchEvent(Events::postFlush, new PostFlushEventArgs($this->em));
2012-07-23 03:14:02 +04:00
}
}
}