/lib/Doctrine/ORM/UnitOfWork.php
PHP | 3192 lines | 1627 code | 512 blank | 1053 comment | 305 complexity | eb17729e4b30c53af577e21b07903adf MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?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
- * and is licensed under the MIT license. For more information, see
- * <http://www.doctrine-project.org>.
- */
- namespace Doctrine\ORM;
- use Exception;
- use InvalidArgumentException;
- use UnexpectedValueException;
- 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;
- 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;
- /**
- * 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>
- * @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;
- /**
- * 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.
- *
- * @var array
- */
- 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.
- * Keys are object ids (spl_object_hash). This is used for calculating changesets
- * at commit time.
- *
- * @var array
- * @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.
- * Keys are object ids (spl_object_hash).
- *
- * @var array
- */
- private $entityStates = array();
- /**
- * 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.
- * Keys are object ids (spl_object_hash).
- *
- * @var array
- * @todo rename: scheduledForSynchronization
- */
- private $scheduledForDirtyCheck = array();
- /**
- * A list of all pending entity insertions.
- *
- * @var array
- */
- private $entityInsertions = array();
- /**
- * A list of all pending entity updates.
- *
- * @var array
- */
- private $entityUpdates = array();
- /**
- * Any pending extra updates that have been scheduled by persisters.
- *
- * @var array
- */
- private $extraUpdates = array();
- /**
- * A list of all pending entity deletions.
- *
- * @var array
- */
- private $entityDeletions = array();
- /**
- * All pending collection deletions.
- *
- * @var array
- */
- private $collectionDeletions = array();
- /**
- * All pending collection updates.
- *
- * @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;
- /**
- * The calculator used to calculate the order in which changes to
- * entities need to be written to the database.
- *
- * @var \Doctrine\ORM\Internal\CommitOrderCalculator
- */
- 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;
- /**
- * The ListenersInvoker used for dispatching events.
- *
- * @var \Doctrine\ORM\Event\ListenersInvoker
- */
- private $listenersInvoker;
- /**
- * 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();
- /**
- * 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);
- }
- /**
- * 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.
- *
- * The operations are executed in the following order:
- *
- * 1) All entity insertions
- * 2) All entity updates
- * 3) All collection deletions
- * 4) All collection updates
- * 5) All entity deletions
- *
- * @param null|object|array $entity
- *
- * @return void
- *
- * @throws \Exception
- */
- public function commit($entity = null)
- {
- // Raise preFlush
- if ($this->evm->hasListeners(Events::preFlush)) {
- $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);
- }
- }
- 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);
- }
- }
- $this->dispatchOnFlushEvent();
- // Now we need a commit order to maintain referential integrity
- $commitOrder = $this->getCommitOrder();
- $conn = $this->em->getConnection();
- $conn->beginTransaction();
- try {
- if ($this->entityInsertions) {
- foreach ($commitOrder as $class) {
- $this->executeInserts($class);
- }
- }
- if ($this->entityUpdates) {
- foreach ($commitOrder as $class) {
- $this->executeUpdates($class);
- }
- }
- // Extra updates that were requested by persisters.
- if ($this->extraUpdates) {
- $this->executeExtraUpdates();
- }
- // Collection deletions (deletions of complete collections)
- foreach ($this->collectionDeletions as $collectionToDelete) {
- $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete);
- }
- // Collection updates (deleteRows, updateRows, insertRows)
- foreach ($this->collectionUpdates as $collectionToUpdate) {
- $this->getCollectionPersister($collectionToUpdate->getMapping())->update($collectionToUpdate);
- }
- // Entity deletions come last and need to be in reverse commit order
- if ($this->entityDeletions) {
- for ($count = count($commitOrder), $i = $count - 1; $i >= 0; --$i) {
- $this->executeDeletions($commitOrder[$i]);
- }
- }
- $conn->commit();
- } catch (Exception $e) {
- $this->em->close();
- $conn->rollback();
- throw $e;
- }
- // Take new snapshots from visited collections
- foreach ($this->visitedCollections as $coll) {
- $coll->takeSnapshot();
- }
- $this->dispatchPostFlushEvent();
- // 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
- *
- * @throws \InvalidArgumentException
- */
- private function computeSingleEntityChangeSet($entity)
- {
- if ( $this->getEntityState($entity) !== self::STATE_MANAGED) {
- throw new \InvalidArgumentException("Entity has to be managed for single computation " . self::objToStr($entity));
- }
- $class = $this->em->getClassMetadata(get_class($entity));
- if ($class->isChangeTrackingDeferredImplicit()) {
- $this->persist($entity);
- }
- // Compute changes for INSERTed entities first. This must always happen even in this case.
- $this->computeScheduleInsertsChangeSets();
- 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);
- }
- }
- /**
- * 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();
- }
- /**
- * Computes the changes that happened to a single entity.
- *
- * Modifies/populates the following properties:
- *
- * {@link _originalEntityData}
- * If the entity is NEW or MANAGED but not yet fully persisted (only has an id)
- * then it was not fetched from the database and therefore we have no original
- * entity data yet. All of the current entity data is stored as the original entity data.
- *
- * {@link _entityChangeSets}
- * The changes detected on all properties of the entity are stored there.
- * A change is a tuple array where the first entry is the old value and the second
- * entry is the new value of the property. Changesets are used by persisters
- * to INSERT/UPDATE the persistent entity state.
- *
- * {@link _entityUpdates}
- * If the entity is already fully MANAGED (has been fetched from the database before)
- * and any changes to its properties are detected, then a reference to the entity is stored
- * there to mark it for an update.
- *
- * {@link _collectionDeletions}
- * If a PersistentCollection has been de-referenced in a fully MANAGED entity,
- * then this collection is marked for deletion.
- *
- * @ignore
- *
- * @internal Don't call from the outside.
- *
- * @param ClassMetadata $class The class descriptor of the entity.
- * @param object $entity The entity for which to compute the changes.
- *
- * @return void
- */
- public function computeChangeSet(ClassMetadata $class, $entity)
- {
- $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);
- if ($invoke !== ListenersInvoker::INVOKE_NONE) {
- $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke);
- }
- $actualData = array();
- foreach ($class->reflFields as $name => $refProp) {
- $value = $refProp->getValue($entity);
- 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);
- }
- $assoc = $class->associationMappings[$name];
- // Inject PersistentCollection
- $value = new PersistentCollection(
- $this->em, $this->em->getClassMetadata($assoc['targetEntity']), $value
- );
- $value->setOwner($entity, $assoc);
- $value->setDirty( ! $value->isEmpty());
- $class->reflFields[$name]->setValue($entity, $value);
- $actualData[$name] = $value;
- continue;
- }
- if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) && ($name !== $class->versionField)) {
- $actualData[$name] = $value;
- }
- }
- 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) {
- if ( ! isset($class->associationMappings[$propName])) {
- $changeSet[$propName] = array(null, $actualValue);
- continue;
- }
- $assoc = $class->associationMappings[$propName];
- if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
- $changeSet[$propName] = array(null, $actualValue);
- }
- }
- $this->entityChangeSets[$oid] = $changeSet;
- } else {
- // Entity is "fully" MANAGED: it was already fully persisted before
- // and we have a copy of the original data
- $originalData = $this->originalEntityData[$oid];
- $isChangeTrackingNotify = $class->isChangeTrackingNotify();
- $changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid]))
- ? $this->entityChangeSets[$oid]
- : array();
- foreach ($actualData as $propName => $actualValue) {
- // skip field, its a partially omitted one!
- if ( ! (isset($originalData[$propName]) || array_key_exists($propName, $originalData))) {
- continue;
- }
- $orgValue = $originalData[$propName];
- // skip if value havent changed
- if ($orgValue === $actualValue) {
- continue;
- }
- // if regular field
- if ( ! isset($class->associationMappings[$propName])) {
- if ($isChangeTrackingNotify) {
- continue;
- }
- $changeSet[$propName] = array($orgValue, $actualValue);
- 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);
- }
- }
- if ($orgValue instanceof PersistentCollection) {
- // A PersistentCollection was de-referenced, so delete it.
- $coid = spl_object_hash($orgValue);
- if (isset($this->collectionDeletions[$coid])) {
- continue;
- }
- $this->collectionDeletions[$coid] = $orgValue;
- $changeSet[$propName] = $orgValue; // Signal changeset, to-many assocs will be ignored.
- continue;
- }
- if ($assoc['type'] & ClassMetadata::TO_ONE) {
- if ($assoc['isOwningSide']) {
- $changeSet[$propName] = array($orgValue, $actualValue);
- }
- if ($orgValue !== null && $assoc['orphanRemoval']) {
- $this->scheduleOrphanRemoval($orgValue);
- }
- }
- }
- if ($changeSet) {
- $this->entityChangeSets[$oid] = $changeSet;
- $this->originalEntityData[$oid] = $actualData;
- $this->entityUpdates[$oid] = $entity;
- }
- }
- // Look for changes in associations of the entity
- foreach ($class->associationMappings as $field => $assoc) {
- if (($val = $class->reflFields[$field]->getValue($entity)) !== null) {
- $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;
- }
- }
- }
- }
- /**
- * 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.
- *
- * @return void
- */
- public function computeChangeSets()
- {
- // Compute changes for INSERTed entities first. This must always happen.
- $this->computeScheduleInsertsChangeSets();
- // Compute changes for other MANAGED entities. Change tracking policies take effect here.
- foreach ($this->identityMap as $className => $entities) {
- $class = $this->em->getClassMetadata($className);
- // Skip class if instances are read-only
- if ($class->isReadOnly) {
- continue;
- }
- // 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();
- }
- foreach ($entitiesToProcess as $entity) {
- // Ignore uninitialized proxy objects
- if ($entity instanceof Proxy && ! $entity->__isInitialized__) {
- continue;
- }
- // 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);
- }
- }
- }
- }
- /**
- * Computes the changes of an association.
- *
- * @param array $assoc
- * @param mixed $value The value of the association.
- *
- * @throws ORMInvalidArgumentException
- * @throws ORMException
- *
- * @return void
- */
- private function computeAssociationChanges($assoc, $value)
- {
- 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")
- // Unwrap. Uninitialized collections will simply be empty.
- $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? array($value) : $value->unwrap();
- $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
- foreach ($unwrappedValue as $key => $entry) {
- $state = $this->getEntityState($entry, self::STATE_NEW);
- if ( ! ($entry instanceof $assoc['targetEntity'])) {
- throw new ORMException(
- sprintf(
- 'Found entity of type %s on association %s#%s, but expecting %s',
- get_class($entry),
- $assoc['sourceEntity'],
- $assoc['fieldName'],
- $targetClass->name
- )
- );
- }
- switch ($state) {
- case self::STATE_NEW:
- if ( ! $assoc['isCascadePersist']) {
- throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($assoc, $entry);
- }
- $this->persistNew($targetClass, $entry);
- $this->computeChangeSet($targetClass, $entry);
- break;
- case self::STATE_REMOVED:
- // Consume the $value as array (it's either an array or an ArrayAccess)
- // and remove the element from Collection.
- if ($assoc['type'] & ClassMetadata::TO_MANY) {
- unset($value[$key]);
- }
- break;
- 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).
- throw ORMInvalidArgumentException::detachedEntityFoundThroughRelationship($assoc, $entry);
- break;
- default:
- // MANAGED associated entities are already taken into account
- // during changeset calculation anyway, since they are in the identity map.
- }
- }
- }
- /**
- * @param \Doctrine\ORM\Mapping\ClassMetadata $class
- * @param object $entity
- *
- * @return void
- */
- private function persistNew($class, $entity)
- {
- $oid = spl_object_hash($entity);
- $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::prePersist);
- if ($invoke !== ListenersInvoker::INVOKE_NONE) {
- $this->listenersInvoker->invoke($class, Events::prePersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
- }
- $idGen = $class->idGenerator;
- if ( ! $idGen->isPostInsertGenerator()) {
- $idValue = $idGen->generate($this->em, $entity);
- if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) {
- $idValue = array($class->identifier[0] => $idValue);
- $class->setIdentifierValues($entity, $idValue);
- }
- $this->entityIdentifiers[$oid] = $idValue;
- }
- $this->entityStates[$oid] = self::STATE_MANAGED;
- $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().
- *
- * 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.
- *
- * @ignore
- *
- * @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.
- */
- 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);
- }
- // skip if change tracking is "NOTIFY"
- if ($class->isChangeTrackingNotify()) {
- return;
- }
- 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];
- $changeSet = array();
- foreach ($actualData as $propName => $actualValue) {
- $orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null;
- if (is_object($orgValue) && $orgValue !== $actualValue) {
- $changeSet[$propName] = array($orgValue, $actualValue);
- } else if ($orgValue != $actualValue || ($orgValue === null ^ $actualValue === null)) {
- $changeSet[$propName] = array($orgValue, $actualValue);
- }
- }
- if ($changeSet) {
- if (isset($this->entityChangeSets[$oid])) {
- $this->entityChangeSets[$oid] = array_merge($this->entityChangeSets[$oid], $changeSet);
- }
- $this->originalEntityData[$oid] = $actualData;
- }
- }
- /**
- * Executes all entity insertions for entities of the specified type.
- *
- * @param \Doctrine\ORM\Mapping\ClassMetadata $class
- *
- * @return void
- */
- 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) {
- if ($this->em->getClassMetadata(get_class($entity))->name !== $className) {
- continue;
- }
- $persister->addInsert($entity);
- unset($this->entityInsertions[$oid]);
- if ($invoke !== ListenersInvoker::INVOKE_NONE) {
- $entities[] = $entity;
- }
- }
- $postInsertIds = $persister->executeInserts();
- if ($postInsertIds) {
- // Persister returned post-insert IDs
- foreach ($postInsertIds as $id => $entity) {
- $oid = spl_object_hash($entity);
- $idField = $class->identifier[0];
- $class->reflFields[$idField]->setValue($entity, $id);
- $this->entityIdentifiers[$oid] = array($idField => $id);
- $this->entityStates[$oid] = self::STATE_MANAGED;
- $this->originalEntityData[$oid][$idField] = $id;
- $this->addToIdentityMap($entity);
- }
- }
- foreach ($entities as $entity) {
- $this->listenersInvoker->invoke($class, Events::postPersist, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
- }
- }
- /**
- * Executes all entity updates for entities of the specified type.
- *
- * @param \Doctrine\ORM\Mapping\ClassMetadata $class
- *
- * @return void
- */
- 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) {
- 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);
- }
- }
- }
- /**
- * Executes all entity deletions for entities of the specified type.
- *
- * @param \Doctrine\ORM\Mapping\ClassMetadata $class
- *
- * @return void
- */
- 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);
- }
- if ($invoke !== ListenersInvoker::INVOKE_NONE) {
- $this->listenersInvoker->invoke($class, Events::postRemove, $entity, new LifecycleEventArgs($entity, $this->em), $invoke);
- }
- }
- }
- /**
- * Gets the commit order.
- *
- * @param array|null $entityChangeSet
- *
- * @return array
- */
- private function getCommitOrder(array $entityChangeSet = null)
- {
- if ($entityChangeSet === null) {
- $entityChangeSet = array_merge($this->entityInsertions, $this->entityUpdates, $this->entityDeletions);
- }
- $calc = $this->getCommitOrderCalculator();
- // See if there are any new classes in the changeset, that are not in the
- // commit order graph yet (dont 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();
- foreach ($entityChangeSet as $entity) {
- $className = $this->em->getClassMetadata(get_class($entity))->name;
- if ($calc->hasClass($className)) {
- continue;
- }
- $class = $this->em->getClassMetadata($className);
- $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;
- }
- $calc->addDependency($targetSubClass, $class);
- }
- }
- }
- return $calc->getCommitOrder();
- }
- /**
- * 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.
- *
- * @return void
- *
- * @throws ORMInvalidArgumentException
- * @throws \InvalidArgumentException
- */
- 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;
- 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
- */
- 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.
- *
- * @return void
- *
- * @throws ORMInvalidArgumentException
- */
- 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.
- *
- * Extra updates for entities are stored as (entity, changeset) tuples.
- *
- * @ignore
- *
- * @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);
- }
- $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
- */
- 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
- */
- public function isScheduledForDirtyCheck($entity)
- {
- $rootEntityName = $this->em->getClassMetadata(get_class($entity))->rootEntityName;
- return isset($this->scheduledForDirtyCheck[$rootEntityName][spl_object_hash($entity)]);
- }
- /**
- * INTERNAL:
- * Schedules an entity for deletion.
- *
- * @param object $entity
- *
- * @return void
- */
- 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]);
- }
- 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
- */
- public function isScheduledForDelete($entity)
- {
- return isset($this->entityDeletions[spl_object_hash($entity)]);
- }
- /**
- * Checks whether an entity is scheduled for insertion, update or deletion.
- *
- * @param object $entity
- *
- * @return boolean
- */
- 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.
- *
- * @ignore
- *
- * @param object $entity The entity to register.
- *
- * @return boolean TRUE if the registration was successful, FALSE if the identity of
- * the entity in question is already managed.
- *
- * @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;
- }
- /**
- * Gets the state of an entity with regard to the current unit of work.
- *
- * @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)) {
- 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;
- }
- }
- /**
- * INTERNAL:
- * Removes an entity from the identity map. This effectively detaches the
- * entity from the persistence management of Doctrine.
- *
- * @ignore
- *
- * @param object $entity
- *
- * @return boolean
- *
- * @throws ORMInvalidArgumentException
- */
- 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;
- }
- /**
- * INTERNAL:
- * Gets an entity in the identity map by its id…
Large files files are truncated, but you can click here to view the full file