public function getEntityState($entity, $assume = null)
{
$oid = spl_object_hash($entity);
if ( ! isset($this->entityStates[$oid])) {
// 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.
if ($assume === null) {
$class = $this->em->getClassMetadata(get_class($entity));
$id = $class->getIdentifierValues($entity);
if ( ! $id) {
return self::STATE_NEW;
} else if ($class->isIdentifierNatural()) {
// Check for a version field, if available, to avoid a db lookup.
if ($class->isVersioned) {
if ($class->getFieldValue($entity, $class->versionField)) {
return self::STATE_DETACHED;
} else {
return self::STATE_NEW;
}
} else {
// Last try before db lookup: check the identity map.
if ($this->tryGetById($id, $class->rootEntityName)) {
return self::STATE_DETACHED;
} else {
// db lookup
if ($this->getEntityPersister(get_class($entity))->exists($entity)) {
return self::STATE_DETACHED;
} else {
return self::STATE_NEW;
}
}
}
} else {
return self::STATE_DETACHED;
}
} else {
return $assume;
}
}
return $this->entityStates[$oid];
}