Doctrine\ODM\MongoDB\UnitOfWork::getDocumentState PHP Method

getDocumentState() public method

Gets the state of a document with regard to the current unit of work.
public getDocumentState ( object $document, integer | null $assume = null ) : integer
$document object
$assume integer | null The state to assume if the state is not yet known (not MANAGED or REMOVED). This parameter can be set to improve performance of document 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 integer The document state.
    public function getDocumentState($document, $assume = null)
    {
        $oid = spl_object_hash($document);
        if (isset($this->documentStates[$oid])) {
            return $this->documentStates[$oid];
        }
        $class = $this->dm->getClassMetadata(get_class($document));
        if ($class->isEmbeddedDocument) {
            return self::STATE_NEW;
        }
        if ($assume !== null) {
            return $assume;
        }
        /* State can only be NEW or DETACHED, because MANAGED/REMOVED states are
         * known. Note that you cannot remember the NEW or DETACHED state in
         * _documentStates 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.
         */
        $id = $class->getIdentifierObject($document);
        if ($id === null) {
            return self::STATE_NEW;
        }
        // Check for a version field, if available, to avoid a DB lookup.
        if ($class->isVersioned) {
            return $class->getFieldValue($document, $class->versionField) ? self::STATE_DETACHED : self::STATE_NEW;
        }
        // Last try before DB lookup: check the identity map.
        if ($this->tryGetById($id, $class)) {
            return self::STATE_DETACHED;
        }
        // DB lookup
        if ($this->getDocumentPersister($class->name)->exists($document)) {
            return self::STATE_DETACHED;
        }
        return self::STATE_NEW;
    }

Usage Example

 function it_schedules_owning_document_for_update_when_setting_element_by_key_in_the_collection(MongoDBODMUnitOfWork $uow, DocumentStub $document, ObjectRepository $repository, ClassMetadata $classMetadata, EntityStub $entity4, EntityStub $entity8, EntityStub $entity15, EntityStub $newEntity)
 {
     $classMetadata->getIdentifier()->willReturn(['id']);
     $repository->findBy(['id' => [4, 8, 15]])->willReturn([$entity4, $entity8, $entity15]);
     $uow->getDocumentState($document)->willReturn(MongoDBODMUnitOfWork::STATE_MANAGED);
     $uow->isScheduledForUpdate($document)->willReturn(false);
     $uow->scheduleForUpdate($document)->shouldBeCalled();
     $this->setOwner($document);
     $this->set(2, $newEntity);
 }
UnitOfWork