save() public method

Saves an object to this collection
public save ( array | object &$a, array $options = [] ) : array | boolean
$a array | object Array to save. If an object is used, it may not have protected or private properties.
$options array Options for the save.
return array | boolean If w was set, returns an array containing the status of the save. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
Beispiel #1
0
 /**
  * Write a message to the log.
  *
  * @param array $event Event data
  * @return void
  * @throws Zend\Log\Exception\RuntimeException
  */
 protected function doWrite(array $event)
 {
     if (null === $this->mongoCollection) {
         throw new RuntimeException('MongoCollection must be defined');
     }
     $this->mongoCollection->save($event, $this->saveOptions);
 }
Beispiel #2
0
 public function save($document)
 {
     $data = $this->objectFactory->marshal($document);
     $this->mongoCollection->save($data);
     $this->objectFactory->setId($document, $data['_id']);
     return $this;
 }
Beispiel #3
0
 /**
  * Write messages
  *
  * @return mixed|void
  */
 public function write()
 {
     foreach ($this->messages as $message) {
         $message['log'] = $this->format($message);
         $this->collection->save($message);
     }
 }
Beispiel #4
0
 /**
  * {@inheritDoc}
  */
 public function persist(Persistable $doc)
 {
     $struc = $this->factory->desegregate($doc);
     if (array_key_exists('id', $struc)) {
         unset($struc['id']);
     }
     if (!is_null($doc->getId())) {
         $struc['_id'] = $doc->getId();
     }
     $this->collection->save($struc);
     $doc->setId($struc['_id']);
 }
Beispiel #5
0
 /**
  * Write Session Data
  *
  * @param string $id
  *   Session Data ID
  *
  * @param string $data
  *   Data to Store
  *
  * @param integer $expires
  *   Expiration Timestamp
  *
  * @return boolean
  *   TRUE on success and FALSE on failure
  */
 public function write($id, $data, $expires)
 {
     if (!empty($_SESSION)) {
         $this->collection->save(array('_id' => $id, 'data' => eval(sprintf('return %s;', preg_replace(array('/\\w+::__set_state\\(/', '/\\)\\)/'), array(NULL, ')'), var_export($_SESSION, TRUE)))), 'serialized' => new \MongoBinData(gzcompress($data)), 'expires' => new \MongoDate(time() + $expires)));
     }
     return TRUE;
 }
Beispiel #6
0
 /**
  * Save data to a the MongoDB collection
  * 
  * @param integer $id
  * @param array $data
  * @param integer $lifetime
  * @param mixed $tags
  * @return boolean
  */
 private function set($id, $data, $lifetime, $tags)
 {
     list($nowMicroseconds, $nowSeconds) = explode(' ', microtime());
     $nowMicroseconds = intval($nowMicroseconds * 1000000);
     //Convert from 'expressed in seconds' to complete microseconds
     return $this->_collection->save(array('_id' => $id, 'd' => $data, 'created_at' => new \MongoDate($nowSeconds, $nowMicroseconds), 'expires_at' => is_numeric($lifetime) && intval($lifetime) !== 0 ? new \MongoDate($nowSeconds + $lifetime, $nowMicroseconds) : null, 't' => $tags, 'hits' => 0));
 }
 /**
  * This writes to memory. 
  * After returning PHP will invoke SessionHandler::close.
  * 
  * @param string $sessionId
  * @param string $data Serialized shit
  * @return boolean
  */
 public function write($sessionId, $data)
 {
     $query = array("session-id" => $sessionId);
     $toSave = array_merge($query, array("data" => $data, "time" => time()));
     try {
         $el = $this->collection->findOne($query);
         if ($el === null) {
             $result = $this->collection->save($toSave);
         } else {
             $result = $this->collection->update($query, $toSave);
         }
         return $result["ok"] == 1;
     } catch (MongoCursorException $ex) {
         return false;
     }
 }
Beispiel #8
0
 /**
  * Execute the save query.
  *
  * @see Collection::save()
  * @param array $a
  * @param array $options
  * @return array|boolean
  */
 protected function doSave(array &$a, array $options)
 {
     $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
     $options = isset($options['wtimeout']) ? $this->convertWriteTimeout($options) : $options;
     $options = isset($options['timeout']) ? $this->convertSocketTimeout($options) : $options;
     return $this->mongoCollection->save($a, $options);
 }
 /**
  * Will add or update an existing object with a matching _id
  * 
  * @param type $value object to save 
  */
 public function save($value)
 {
     ValidatorsUtil::isNullOrEmpty($this->_mongoCollection, "Mongo collection isn't valid, have you set a collection?");
     ValidatorsUtil::isNull($value, "Must have a valid object to insert in collection");
     $this->_mongoCollection->save($value);
     $this->_count = 0;
 }
Beispiel #10
0
 /**
  * @param int $id
  * @param array $data
  * @param int $lifetime
  * @param mixed $tags
  * @return boolean
  */
 public function set($id, $data, $lifetime, $tags)
 {
     $now = time();
     // set the lifetime to 1 year if it is null
     if (!$lifetime) {
         $lifetime = 86400 * 365;
     }
     return $this->_collection->save(['_id' => $id, 'd' => $data, 'created_at' => $now, 'l' => $lifetime, 'expire' => $now + $lifetime, 't' => $tags]);
 }
Beispiel #11
0
 /**
  * Saving record to the database
  * @param boolean $validate Validate record before saving
  * @param boolean $throw Throw an expcetion if an error occured
  * @return boolean Operation success mark
  * @throws \MongoAR\Exception If an error occured and $throw is set to TRUE
  * @since 0.1
  */
 public function save($validate = true, $throw = false)
 {
     if ($this->id) {
         $this->document['_id'] = $this->id;
     }
     $response = $this->table->save($this->document);
     $this->fetchId($this->document);
     return $this->checkResponse($response, $throw);
 }
Beispiel #12
0
 /**
  * {@inheritdoc}
  */
 public function storeData($key, $data, $expiration)
 {
     if ($this->collection instanceof \MongoDB\Collection) {
         $id = self::mapKey($key);
         try {
             $this->collection->replaceOne(['_id' => $id], ['_id' => $id, 'data' => serialize($data), 'expiration' => $expiration], ['upsert' => true]);
         } catch (\MongoDB\Driver\Exception\BulkWriteException $ignored) {
             // As of right now, BulkWriteException can be thrown by replaceOne in high-throughput environments where race conditions can occur
         }
     } else {
         try {
             $this->collection->save(['_id' => self::mapKey($key), 'data' => serialize($data), 'expiration' => $expiration]);
         } catch (\MongoDuplicateKeyException $ignored) {
             // Because it's Mongo, we might have had this problem because of a cache stampede
         }
     }
     return true;
 }
Beispiel #13
0
 /**
  * Write a profile to the mongo database
  *
  * @param array $profile Profiler Collected Data
  * @return void
  * @throws Exception\RuntimeException
  */
 public function save(array $profile)
 {
     if (null === $this->mongoCollection) {
         throw new Exception\RuntimeException('MongoCollection must be defined');
     }
     if ($this->hostname !== 'all') {
         $profile['report']['hostname'] = $this->hostname;
     }
     $this->mongoCollection->save($profile, $this->saveOptions);
 }
Beispiel #14
0
 /**
  * Write a message to the log.
  *
  * @param array $event Event data
  * @return void
  * @throws Zend\Log\Exception\RuntimeException
  */
 protected function doWrite(array $event)
 {
     if (null === $this->mongoCollection) {
         throw new RuntimeException('MongoCollection must be defined');
     }
     if (isset($event['timestamp']) && $event['timestamp'] instanceof DateTime) {
         $event['timestamp'] = new MongoDate($event['timestamp']->getTimestamp());
     }
     $this->mongoCollection->save($event, $this->saveOptions);
 }
 public function testGroup2()
 {
     $this->object->save(array("a" => 2));
     $this->object->save(array("b" => 5));
     $this->object->save(array("a" => 1));
     $keys = array();
     $initial = array("count" => 0);
     $reduce = "function (obj, prev) { prev.count++; }";
     $g = $this->object->group($keys, $initial, $reduce);
     $this->assertEquals(3, $g['count']);
 }
 /**
  * Saves a document into the model's collection. If the object exists, update the existing database object, otherwise insert this object.
  * @param array $document Array of data fields of the document
  * @param array $options Options for the insert see @link http://www.php.net/manual/en/mongocollection.save.php
  * @param bool  $returnId return the saved document mongo id
  * @return mixed If safe was set, returns an array containing the status of the save. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
  * Throws MongoCursorException if the "safe" option is set and the save fails. Throws MongoCursorTimeoutException if the "safe" option is set and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout.
  */
 public function save($document, $options = array(), $returnId = true)
 {
     if ($options === null) {
         $options = array();
     }
     $document = self::_sanitize($document);
     if ($returnId) {
         $this->collection->save($document, $options);
         return $document['_id'];
     }
     return $this->collection->save($document, $options);
 }
Beispiel #17
0
 /**
  * Set a value based on an id. Optionally add tags.
  *
  * @param   string   $id        id
  * @param   mixed    $data      data
  * @param   integer  $lifetime  lifetime [Optional]
  * @param   array    $tags      tags [Optional]
  * @return  boolean
  * @throws  Cache_Exception
  */
 public function set_with_tags($id, $data, $lifetime = NULL, array $tags = NULL)
 {
     // Setup lifetime
     if ($lifetime === NULL) {
         $lifetime = 0 === Arr::get($this->_config, 'default_expire', NULL) ? 0 : Arr::get($this->_config, 'default_expire', Cache::DEFAULT_EXPIRE) + time();
     } else {
         $lifetime = 0 === $lifetime ? 0 : $lifetime + time();
     }
     $data = serialize($data);
     $doc = array('_id' => $id, 'data' => $data, 'tags' => !empty($tags) ? $tags : array(), 'lifetime' => $lifetime);
     return (bool) $this->_collection->save($doc);
 }
 /**
  * {@inheritdoc}
  */
 public function set($cid, $data, $expire = CACHE_PERMANENT)
 {
     $scalar = is_scalar($data);
     $entry = array('_id' => (string) $cid, 'cid' => (string) $cid, 'created' => REQUEST_TIME, 'expire' => $expire, 'serialized' => !$scalar, 'data' => $scalar ? $data : serialize($data));
     // Use MongoBinData for non-UTF8 strings.
     if (is_string($entry['data']) && !drupal_validate_utf8($entry['data'])) {
         $entry['data'] = $this->createBinData($entry['data']);
     }
     try {
         $this->collection->save($entry, $this->unsafe);
     } catch (\Exception $e) {
         // The database may not be available, so we'll ignore cache_set requests.
     }
 }
 public function testGroup()
 {
     $g = $this->object->group(array(), array("count" => 0), "function (obj, prev) { prev.count++; }", array());
     $this->assertEquals(0, count($g['retval']));
     $this->object->save(array("a" => 2));
     $this->object->save(array("b" => 5));
     $this->object->save(array("a" => 1));
     $g = $this->object->group(array(), array("count" => 0), "function (obj, prev) { prev.count++; }", array());
     $this->assertEquals(1, count($g['retval']));
     $this->assertEquals(3, $g['retval'][0]['count']);
     $g = $this->object->group(array(), array("count" => 0), "function (obj, prev) { prev.count++; }", array("a" => array('$gt' => 1)));
     $this->assertEquals(1, count($g['retval']));
     $this->assertEquals(1, $g['retval'][0]['count']);
 }
 /**
  * Saves a given entity or set of entities.
  * Use the returned instance for further operations as
  * the save operation might have changed the entity instance completely.
  * @param MongoEntity|MongoEntity[] $param an entitiy or set of entities
  * @return MongoEntity|MongoEntity[] the saved entity or entities
  */
 public function save($param)
 {
     if (is_array($param)) {
         foreach ($param as $p) {
             if ($p instanceof MongoEntity) {
                 $this->save($p);
             }
         }
     } else {
         if ($param instanceof MongoEntity) {
             $doc = $param->getAttributes();
             if ($param->getId()) {
                 $doc['_id'] = new MongoId($param->getId());
             } else {
                 $doc['_id'] = new MongoId();
             }
             $this->collection->save($doc);
             $param->setId($doc['_id']);
         }
     }
     return $param;
 }
 /**
  * Save the session data.
  * @param  string  $sid  The session ID that PHP passes.
  * @param  string  $data The session serialized data string.
  * @return boolean True always.
  */
 public function write($sid, $data)
 {
     //update/insert our session data
     if (!$this->sessionDoc) {
         $this->sessionDoc = array();
         $this->sessionDoc['_id'] = $sid;
         $this->sessionDoc['started'] = new MongoDate();
     }
     //there could have been a session regen so we need to be careful with the $sid here and set it anyway
     if ($this->sid != $sid) {
         //need to unlock old sid
         $this->unlock($this->sid);
         //set the new one
         $this->sid = $sid;
         $this->lock($this->sid);
         //@TODO shouldn't we try to see if this succeeded first?
         //and also make sure we're going to write to the correct document
         $this->sessionDoc['_id'] = $sid;
     }
     $this->sessionDoc['last_accessed'] = new MongoDate();
     $this->sessionDoc['data'] = new MongoBinData($data, MongoBinData::BYTE_ARRAY);
     $this->sessions->save($this->sessionDoc, $this->getConfig('write_options'));
     return true;
 }
Beispiel #22
0
 /**
  * {@inheritdoc}
  */
 protected function rollbackTransaction()
 {
     if (!empty($this->rollbackRecords)) {
         switch ($this->getAction()) {
             case Verbs::POST:
                 // should be ids here from creation
                 $filter = [static::DEFAULT_ID_FIELD => ['$in' => $this->rollbackRecords]];
                 $this->collection->remove($filter);
                 break;
             case Verbs::PUT:
             case Verbs::PATCH:
             case Verbs::MERGE:
             case Verbs::DELETE:
                 foreach ($this->rollbackRecords as $record) {
                     $this->collection->save($record);
                 }
                 break;
             default:
                 break;
         }
         $this->rollbackRecords = [];
     }
     return true;
 }
Beispiel #23
0
 protected function doSave(array &$a, array $options)
 {
     return $this->mongoCollection->save($a, $options);
 }
Beispiel #24
0
 /**
  * Saves a document to this collection
  * @link http://php.net/manual/en/mongocollection.save.php
  * 
  * @param array|object $doc      Array or object to save.
  * @param array        $options  Options for the save.
  * @return array|boolean
  */
 public function save(&$doc, array $options = [])
 {
     $values = $this->db->toMongoType($doc);
     $ret = parent::save($values, $options);
     $this->setDocId($doc, $values);
     return $ret;
 }
 /**
  * Saves the quote in MongoDB.
  *
  * @todo: update insertQuote() to use saveQuote() or refactor code
  *        to use saveQuote() as save() does automatically choose correctly
  *        between update and insert.
  *
  * @return void
  */
 public function saveQuote()
 {
     $this->setState(self::QUOTE);
     $data = array('_id' => new MongoId($this->getId()), 'state' => $this->getState(), 'items' => $this->getItems(), 'quote_id' => $this->getQuoteId());
     $this->_tblSales->save($data);
 }
 public function save(ExpenseListInOverview $readModel)
 {
     $this->collection->save($readModel->serialize());
 }
                    $maxId = $newMaxId;
                } else {
                    echo 'sleep-1-20s \\n';
                    sleep(20);
                    $startId++;
                }
                echo 'sleep-2-10s \\n';
                sleep(10);
                continue;
            }
            $back = RequestUtil::getUrl(BiliBiliHelper::$SERVICE_URL . "/view/{$startId}");
            if ($back['code'] != 200) {
                echo 'sleep-3-10s \\n';
                sleep(10);
                $startId++;
                continue;
            }
            echo strval($startId) . '\\n';
            $content = $back['content'];
            $content['aid'] = $startId;
            $content["_id"] = $startId;
            $collVideos->save($content);
            $collection->save(array("_id" => 1, "startId" => $startId));
            $startId++;
            sleep(8);
        }
    } catch (\Exception $e) {
        dd($e);
    }
    sleep(60);
}
Beispiel #28
0
 /**
  * save.
  */
 public function save($a, array $options = array())
 {
     $this->time->start();
     $return = parent::save($a, $options);
     $time = $this->time->stop();
     $this->log(array('type' => 'save', 'a' => $a, 'options' => $options, 'time' => $time));
     return $return;
 }
Beispiel #29
0
 protected function _call($command, array $arguments = array(), array $values = NULL)
 {
     $start = microtime(true);
     $this->_connected or $this->connect();
     extract($arguments);
     if (isset($collection_name)) {
         $c = new \MongoCollection($this->_db, $collection_name);
     }
     switch ($command) {
         case 'ensure_index':
             $r = $c->ensureIndex($keys, $options);
             break;
         case 'create_collection':
             $r = $this->_db->createCollection($name, $capped, $size, $max);
             break;
         case 'drop_collection':
             $r = $this->_db->dropCollection($name);
             break;
         case 'command':
             $r = $this->_db->command($values);
             break;
         case 'execute':
             $r = $this->_db->execute($code, $args);
             break;
         case 'batch_insert':
             $r = $c->batchInsert($values);
             break;
         case 'count':
             $r = $c->count($query);
             break;
         case 'find_one':
             $r = $c->findOne($query, $fields);
             break;
         case 'find':
             $r = $c->find($query, $fields);
             break;
         case 'group':
             $r = $c->group($keys, $initial, $reduce, $condition);
             break;
         case 'update':
             $r = $c->update($criteria, $values, $options);
             break;
         case 'insert':
             $r = $c->insert($values, $options);
             return $values;
             break;
         case 'remove':
             $r = $c->remove($criteria, $options);
             break;
         case 'save':
             $r = $c->save($values, $options);
             break;
         case 'get_file':
             $r = $this->gridFS()->findOne($criteria);
             break;
         case 'get_files':
             $r = $this->gridFS()->find($query, $fields);
             break;
         case 'set_file_bytes':
             $r = $this->gridFS()->storeBytes($bytes, $extra, $options);
             break;
         case 'set_file':
             $r = $this->gridFS()->storeFile($filename, $extra, $options);
             break;
         case 'remove_file':
             $r = $this->gridFS()->remove($criteria, $options);
             break;
     }
     $this->log($command, $start, $arguments);
     return $r;
 }
 public function save(AccountCredentials $accountCredentials)
 {
     $this->collection->save($accountCredentials->toPersistableState());
 }