public function update($document, array $options = array())
{
$id = $this->uow->getDocumentIdentifier($document);
$update = $this->dp->prepareUpdateData($document);
if ( ! empty($update)) {
$id = $this->class->getDatabaseIdentifierValue($id);
$query = array('_id' => $id);
// Include versioning updates
if ($this->class->isVersioned) {
$versionMapping = $this->class->fieldMappings[$this->class->versionField];
$currentVersion = $this->class->getFieldValue($document, $this->class->versionField);
if ($versionMapping['type'] === 'int') {
$nextVersion = $currentVersion + 1;
$update[$this->cmd . 'inc'][$versionMapping['name']] = 1;
$query[$versionMapping['name']] = $currentVersion;
$this->class->setFieldValue($document, $this->class->versionField, $nextVersion);
} elseif ($versionMapping['type'] === 'date') {
$nextVersion = new \DateTime();
$update[$this->cmd . 'set'][$versionMapping['name']] = new \MongoDate($nextVersion->getTimestamp());
$query[$versionMapping['name']] = new \MongoDate($currentVersion->getTimestamp());
$this->class->setFieldValue($document, $this->class->versionField, $nextVersion);
}
$options['safe'] = true;
}
if ($this->class->isLockable) {
$isLocked = $this->class->getFieldValue($document, $this->class->lockField);
$lockMapping = $this->class->fieldMappings[$this->class->lockField];
if ($isLocked) {
$update[$this->cmd . 'unset'] = array($lockMapping['name'] => true);
} else {
$query[$lockMapping['name']] = array($this->cmd . 'exists' => false);
}
}
if ($this->dm->getEventManager()->hasListeners(Events::onUpdatePrepared)) {
$this->dm->getEventManager()->dispatchEvent(
Events::onUpdatePrepared, new OnUpdatePreparedArgs($this->dm, $document, $update)
);
}
$result = $this->collection->update($query, $update, $options);
if (($this->class->isVersioned || $this->class->isLockable) && ! $result['n']) {
throw LockException::lockFailed($document);
}
}
}