public function save()
{
$dependencyInjector = $this->_dependencyInjector;
if (!is_object($dependencyInjector)) {
throw new Exception("A dependency injector container is required to obtain the services related to the ORM");
}
$source = $this->getSource();
if (empty($source)) {
throw new Exception("Method getSource() returns empty string");
}
$connection = $this->getConnection();
$collection = $connection->selectCollection($source);
$exists = $this->_exists($collection);
if (false === $exists) {
$this->_operationMade = self::OP_CREATE;
} else {
$this->_operationMade = self::OP_UPDATE;
}
/**
* The messages added to the validator are reset here
*/
$this->_errorMessages = [];
$disableEvents = self::$_disableEvents;
/**
* Execute the preSave hook
*/
if (false === $this->_preSave($dependencyInjector, $disableEvents, $exists)) {
return false;
}
$data = $this->toArray();
/**
* We always use safe stores to get the success state
* Save the document
*/
switch ($this->_operationMade) {
case self::OP_CREATE:
$status = $collection->insertOne($data);
break;
case self::OP_UPDATE:
$status = $collection->updateOne(['_id' => $this->_id], ['$set' => $this->toArray()]);
break;
default:
throw new Exception('Invalid operation requested for MongoCollection->save()');
}
$success = false;
if ($status->isAcknowledged()) {
$success = true;
if (false === $exists) {
$this->_id = $status->getInsertedId();
}
}
/**
* Call the postSave hooks
*/
return $this->_postSave($disableEvents, $success, $exists);
}