Example #1
0
 /**
  * @return bool|void
  * @throws \Exception
  */
 public function save()
 {
     $this->__operation = 'save';
     $source = $this->getSource();
     if (empty($source)) {
         throw new \Exception("Method getSource() returns empty string");
     }
     $connection = $this->getConnection();
     /**
      * Choose a collection according to the collection name
      */
     $collection = $connection->selectCollection($source);
     /**
      * Check the dirty state of the current operation to update the current operation
      */
     $exists = parent::_exists($collection);
     if ($exists === false) {
         $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 (parent::_preSave($this->getDI(), $disableEvents, $exists) === false) {
         return false;
     }
     $data = $this->toArray();
     $metadata = $this->getMetadata();
     $currentValues = [];
     if (!empty($metadata)) {
         foreach ($this->getObjectProperties() as $object => $value) {
             if (isset($metadata[$object])) {
                 $currentValues[$object] = $this->{$object};
                 if (Scalar::isScalar($metadata[$object])) {
                     $data[$object] = Scalar::map($this->{$object}, $metadata[$object]);
                 } else {
                     $reflectionClass = new \ReflectionClass($metadata[$object]);
                     if ($reflectionClass->isSubclassOf(MapperInterface::class)) {
                         $data[$object] = $reflectionClass->getMethod('createReference')->invoke(null, $this->{$object});
                     }
                 }
             }
         }
     }
     $success = false;
     $status = $collection->save($data, ["w" => true]);
     if (is_array($status)) {
         if (isset($status['ok'])) {
             if ($status['ok']) {
                 $success = true;
                 if ($exists === false) {
                     if (isset($data['_id'])) {
                         $this->_id = $data['_id'];
                     }
                 }
             }
         }
     } else {
         $success = false;
     }
     // clears cache for saved document
     if ($success) {
         $this->clearEntityMappingCache($this->_id);
     }
     $this->__operation = false;
     /**
      * Call the postSave hooks
      */
     return parent::_postSave($disableEvents, $success, $exists);
 }