public function testCreate()
 {
     $collection = "d";
     $id = 123;
     $db = "phpunit_temp";
     $ref = MongoDBRef::create($collection, $id);
     $this->assertEquals("d", $ref['$ref'], json_encode($ref));
     $this->assertEquals(123, $ref['$id'], json_encode($ref));
     $this->assertArrayNotHasKey('$db', $ref, json_encode($ref));
     $ref = MongoDBRef::create($collection, $id, $db);
     $this->assertEquals("d", $ref['$ref'], json_encode($ref));
     $this->assertEquals(123, $ref['$id'], json_encode($ref));
     $this->assertEquals("phpunit_temp", $ref['$db'], json_encode($ref));
     // test converting to strings
     $ref = MongoDBRef::create(1, 2, 3);
     $this->assertEquals("1", $ref['$ref'], json_encode($ref));
     $this->assertEquals(2, $ref['$id'], json_encode($ref));
     $this->assertEquals("3", $ref['$db'], json_encode($ref));
     // more for tracking this behavior than condoning it...
     $one = 1;
     $two = 2;
     $three = 3;
     $ref = MongoDBRef::create(1, 2, 3);
     $this->assertEquals("1", $one);
     $this->assertEquals(2, $two);
     $this->assertEquals("3", $three);
 }
Example #2
0
 public function InsertCollection($obj, $id)
 {
     //Insert obj values into Collection
     if (!is_null($obj) || !is_null($this->Collect)) {
         $this->Collect->remove();
     }
     if (!is_null($id)) {
         $obj['_id'] = $id;
     }
     echo $obj["Thing"];
     $Recipe = $obj["Recipe"];
     $RecipeCollection = $this->dbObj->selectCollection("RecipeTest");
     $RecipeCollection->Insert($Recipe);
     //echo $Recipe['_id'].'\n';
     $RecipeRef = MongoDBRef::create($RecipeCollection->getName(), $Recipe['_id']);
     $CreativeWork = $obj["CreativeWork"];
     $CreativeWork["RecipeReference"] = $RecipeRef;
     $CreativeWorkCollection = $this->dbObj->selectCollection("CreativeWorkTest");
     $CreativeWorkCollection->Insert($CreativeWork);
     //echo $CreativeWork['_id'];
     $CreativeWrokRef = MongoDBRef::create($CreativeWorkCollection->getName(), $CreativeWork['_id']);
     $thing = $obj["Thing"];
     $thing["CreativeWorkRef"] = $CreativeWrokRef;
     $thingCollection = $this->dbObj->selectCollection("Thingtest");
     $thingCollection->Insert($thing);
     //Back ref
     $recipeback = $this->dbObj->RecipeTest;
     $RecipeResult = $recipeback->findOne(array("ingredients" => "suth"));
     echo 'Result' . $RecipeResult['_id'];
     print_r($RecipeResult);
     $CWback = $this->dbObj->CreativeWorkTest;
     //$CWbackResult = MongoDBRef::get($CWback->db, $RecipeResult['_id']);
     $CWbackResult = $CWback->findOne(array("about" => "test1"));
     print_r($CWbackResult);
 }
Example #3
0
 public function testShouldReturnLazyLoadingCursor()
 {
     $parentCategory = new Category();
     $parentCategory->setName('Parent category');
     $parentCategory->setDesc('Parent category');
     $parentCategory->save();
     for ($i = 0; $i < 10; $i++) {
         $category = new Category();
         $category->setName('Category ' . $i);
         $category->setDesc('Category ' . $i . ' desc');
         $category->setCategory($parentCategory);
         $category->save();
     }
     Category::enableLazyLoading();
     $categories = Category::find([['category' => ['$ne' => null]]]);
     $this->assertInstanceOf('\\Vegas\\Odm\\Collection\\LazyLoadingCursor', $categories);
     foreach ($categories as $category) {
         $this->assertInstanceOf('\\Fixtures\\Collection\\Category', $category);
         $this->assertInstanceOf('\\Fixtures\\Collection\\Category', $category->getCategory());
     }
     $categories = Category::find([['category' => ['$ne' => null]]]);
     $this->assertInstanceOf('\\Vegas\\Odm\\Collection\\LazyLoadingCursor', $categories);
     foreach ($categories as $category) {
         $this->assertInstanceOf('\\Fixtures\\Collection\\Category', $category);
         $reflectionClass = new \ReflectionClass(get_class($category));
         $categoryProperty = $reflectionClass->getProperty('category');
         $categoryProperty->setAccessible(true);
         $this->assertTrue(\MongoDBRef::isRef($categoryProperty->getValue($category)));
     }
 }
Example #4
0
 /**
  * Creates a new database reference
  *
  * @param string|\Phalcon\Mvc\Collection $collection
  * @param mixed|\MongoId|\Phalcon\Mvc\Collection $id
  * @param string $database
  * @return array
  */
 public static function create($collection, $id = null, $database = null)
 {
     if ($collection instanceof \Phalcon\Mvc\Collection) {
         $id = $collection->getId();
         $collection = $collection->getSource();
     }
     if ($id instanceof \Phalcon\Mvc\Collection) {
         $id = $id->getId();
     }
     if (is_array($collection) && self::isRef($collection)) {
         if (isset($collection['$id'])) {
             $id = $collection['$id'];
         }
         if (isset($collection['$ref'])) {
             $collection = $collection['$ref'];
         }
     }
     if (!$id instanceof \MongoId && $id !== null) {
         $id = new \MongoId($id);
     }
     if ($collection instanceof \MongoId) {
         return $collection;
     }
     if ($id === null) {
         return null;
     }
     return parent::create($collection, $id, $database);
 }
Example #5
0
 /**
 * Returns true if the value passed appears to be a Mongo database reference
 *
 * @param mixed $obj
 * @return boolean
 **/
 static function isRef($value)
 {
     if (!is_array($value)) {
         return false;
     }
     return MongoDBRef::isRef($value);
 }
Example #6
0
 /**
  * method to convert plans names into their refs
  * triggered before save the rate entity for edit
  * 
  * @param Mongodloid collection $collection
  * @param array $data
  * 
  * @return void
  * @todo move to model
  */
 public function update($data)
 {
     if (isset($data['rates'])) {
         $plansColl = Billrun_Factory::db()->plansCollection();
         $currentDate = new MongoDate();
         $rates = $data['rates'];
         //convert plans
         foreach ($rates as &$rate) {
             if (isset($rate['plans'])) {
                 $sourcePlans = (array) $rate['plans'];
                 // this is array of strings (retreive from client)
                 $newRefPlans = array();
                 // this will be the new array of DBRefs
                 unset($rate['plans']);
                 foreach ($sourcePlans as &$plan) {
                     if (MongoDBRef::isRef($plan)) {
                         $newRefPlans[] = $plan;
                     } else {
                         $planEntity = $plansColl->query('name', $plan)->lessEq('from', $currentDate)->greaterEq('to', $currentDate)->cursor()->setReadPreference(Billrun_Factory::config()->getConfigValue('read_only_db_pref'))->current();
                         $newRefPlans[] = $planEntity->createRef($plansColl);
                     }
                 }
                 $rate['plans'] = $newRefPlans;
             }
         }
         $data['rates'] = $rates;
     }
     return parent::update($data);
 }
Example #7
0
 public function getReference()
 {
     $collection = collection::forClass($this->_className)->select();
     if (null != $this->_model) {
         $this->_model->save();
     }
     $id = $this->getId();
     return \MongoDBRef::create($collection->getName(), $id, (string) $collection->db);
 }
 public function testRef()
 {
     ini_set("mongo.cmd", ":");
     $this->object->insert(array("_id" => 123, "hello" => "world"));
     $this->object->insert(array("_id" => 456, "ref" => array(":ref" => "bar", ":id" => 123)));
     $ref = $this->object->findOne(array("_id" => 456));
     $obj = MongoDBRef::get($this->object->db, $ref["ref"]);
     $this->assertNotNull($obj);
     $this->assertEquals("world", $obj["hello"], json_encode($obj));
 }
Example #9
0
 function __construct(Glutton $glutton, $data = null, AxonCollection $parent = null, $position = null)
 {
     $this->_glutton = $glutton;
     if (\MongoDBRef::isRef($data)) {
         $this->_reference = Reader::simplifyReference($data);
         $data = array_diff_key($data, $this->_reference);
     }
     $this->_elements = $data;
     $this->_parent = $parent;
     $this->_position = $position;
 }
Example #10
0
 /**
  * Import an account.
  * 
  * @param string $username The username to use.
  * @param string $password The password to use.
  */
 public function import($username, $password)
 {
     $data = $this->get($username);
     $this->db->remove(array('username' => $this->clean($username)));
     $users = new users(ConnectionFactory::get('mongo'));
     $id = $users->create($username, $password, $data['email'], $data['hideEmail'], $this->groups[$data['mgroup']], true);
     $newRef = MongoDBRef::create('users', $id);
     $oldRef = MongoDBRef::create('unimportedUsers', $data['_id']);
     $this->mongo->news->update(array('user' => $oldRef), array('$set' => array('user' => $newRef)));
     $this->mongo->articles->update(array('user' => $oldRef), array('$set' => array('user' => $newRef)));
     self::ApcPurge('get', $data['_id']);
 }
Example #11
0
 public function populateDb()
 {
     $this->_users = array('bob' => array('_id' => new MongoId('4c04516a1f5f5e21361e3ab0'), '_type' => array('My_ShantyMongo_Teacher', 'My_ShantyMongo_User'), 'name' => array('first' => 'Bob', 'last' => 'Jones'), 'addresses' => array(array('street' => '19 Hill St', 'suburb' => 'Brisbane', 'state' => 'QLD', 'postcode' => '4000', 'country' => 'Australia'), array('street' => '742 Evergreen Terrace', 'suburb' => 'Springfield', 'state' => 'Nevada', 'postcode' => '89002', 'country' => 'USA')), 'friends' => array(MongoDBRef::create('user', new MongoId('4c04516f1f5f5e21361e3ab1')), MongoDBRef::create('user', new MongoId('4c0451791f5f5e21361e3ab2')), MongoDBRef::create('user', new MongoId('broken reference'))), 'faculty' => 'Maths', 'email' => '*****@*****.**', 'sex' => 'M', 'partner' => MongoDBRef::create('user', new MongoId('4c04516f1f5f5e21361e3ab1')), 'bestFriend' => MongoDBRef::create('user', new MongoId('4c0451791f5f5e21361e3ab2'))), 'cherry' => array('_id' => new MongoId('4c04516f1f5f5e21361e3ab1'), '_type' => array('My_ShantyMongo_Student', 'My_ShantyMongo_User'), 'name' => array('first' => 'Cherry', 'last' => 'Jones'), 'email' => '*****@*****.**', 'sex' => 'F', 'concession' => true), 'roger' => array('_id' => new MongoId('4c0451791f5f5e21361e3ab2'), '_type' => array('My_ShantyMongo_ArtStudent', 'My_ShantyMongo_Student', 'My_ShantyMongo_User'), 'name' => array('first' => 'Roger', 'last' => 'Smith'), 'email' => '*****@*****.**', 'sex' => 'M', 'concession' => false));
     $this->_userCollection = $this->_connection->selectDb(TESTS_SHANTY_MONGO_DB)->selectCollection('user');
     foreach ($this->_users as $user) {
         $this->_userCollection->insert($user, true);
     }
     $this->_articles = array('regular' => array('_id' => new MongoId('4c04516f1f5f5e21361e3ac1'), 'title' => 'How to use Shanty Mongo', 'author' => MongoDBRef::create('user', new MongoId('4c04516a1f5f5e21361e3ab0')), 'editor' => MongoDBRef::create('user', new MongoId('4c04516f1f5f5e21361e3ab1')), 'contributors' => array(MongoDBRef::create('user', new MongoId('4c04516f1f5f5e21361e3ab1')), MongoDBRef::create('user', new MongoId('4c0451791f5f5e21361e3ab2'))), 'relatedArticles' => array(MongoDBRef::create('article', new MongoId('4c04516f1f5f5e21361e3ac2'))), 'tags' => array('awesome', 'howto', 'mongodb')), 'broken' => array('_id' => new MongoId('4c04516f1f5f5e21361e3ac2'), 'title' => 'How to use Bend Space and Time', 'author' => MongoDBRef::create('user', new MongoId('broken_reference')), 'tags' => array('physics', 'hard', 'cool')));
     $this->_articleCollection = $this->_connection->selectDb(TESTS_SHANTY_MONGO_DB)->selectCollection('article');
     foreach ($this->_articles as $article) {
         $this->_articleCollection->insert($article, true);
     }
 }
Example #12
0
 /**
  * Transform the value in a MongoDBRef if needed
  * @param $attr
  * @param $value
  * @return mixed
  */
 protected function _val($attr, $value)
 {
     $reference = \Rocketr\Schema\Reference::get($this->get_collection_name(), $attr);
     $collection = \Rocketr\Schema\HasCollection::get($this->get_collection_name(), $attr);
     if ($reference xor $collection) {
         $ref_attr = \Rocketr\Schema\Map::on($this->get_collection_name(), $attr);
         $_id = is_array($value) && isset($value[$ref_attr]) || is_object($value) && $value->{$ref_attr} ? is_array($value) ? $value[$ref_attr] : $value->{$ref_attr} : $value;
         $target = $reference ? $reference : $collection;
         $_id = $ref_attr == '_id' && \MongoId::isValid($_id) ? new \MongoId($_id) : $_id;
         return \MongoDBRef::create($target, $_id);
     } else {
         return $value;
     }
 }
Example #13
0
 /**
  * for every rate who has ref to original plan add ref to new plan
  * @param type $source_id
  * @param type $new_id
  */
 public function duplicate_rates($source_id, $new_id)
 {
     $rates_col = Billrun_Factory::db()->ratesCollection();
     $source_ref = MongoDBRef::create("plans", $source_id);
     $dest_ref = MongoDBRef::create("plans", $new_id);
     $usage_types = Billrun_Factory::config()->getConfigValue('admin_panel.line_usages');
     foreach ($usage_types as $type => $string) {
         $attribute = "rates." . $type . ".plans";
         $query = array($attribute => $source_ref);
         $update = array('$push' => array($attribute => $dest_ref));
         $params = array("multiple" => 1);
         $rates_col->update($query, $update, $params);
     }
 }
Example #14
0
 /**
  * Creates a new database reference
  *
  * @param string|\Phalcon\Mvc\Collection $collection
  * @param mixed|\MongoId|\Phalcon\Mvc\Collection $id
  * @param string $database
  * @return array
  */
 public static function create($collection, $id = null, $database = null)
 {
     if ($collection instanceof \Phalcon\Mvc\Collection) {
         $id = $collection->getId();
         $collection = $collection->getSource();
     }
     if ($id instanceof \Phalcon\Mvc\Collection) {
         $id = $id->getId();
     }
     if (!$id instanceof \MongoId && $id !== null) {
         $id = new \MongoId($id);
     }
     return parent::create($collection, $id, $database);
 }
Example #15
0
	public function setReference($name, Base $object = null) {
		if (!in_array($name, static::$_references)) {
			throw new Exception("Document doesn't reference {$name}");
		}

		$this->_referenced[$name] = $object;

		if ($object === null) {
			$this->_data[$name] = null;
		} else {
			$class = get_class($object);
			$this->_data[$name] = \MongoDBRef::create($class::collection()->getName(), $object->mongoId());
		}

		$this->_flagAttributeAsModified($name);
	}
 public function testExtendedDBRef()
 {
     $targetCollection = $this->getCollection('simpleTarget');
     $targetId = new \MongoId();
     $extends = [];
     list($ref, $sourceDocument) = $this->createReferencedDocument($extends, true);
     //extending by embedding some data
     $ref['data'] = $sourceDocument['data'];
     $targetDocument = ['_id' => $targetId, 'ref' => $ref, 'text' => 'amasource'];
     $targetCollection->save($targetDocument);
     $targetDocumentFromDB = $targetCollection->findOne(['_id' => $targetId]);
     $this->assertTrue(\MongoDBRef::isRef($targetDocumentFromDB['ref']));
     $sourceDocumentFromDB = $this->getSourceCollection()->getDBRef($targetDocumentFromDB['ref']);
     $this->assertEquals($sourceDocument, $sourceDocumentFromDB);
     $this->assertEquals($sourceDocumentFromDB['data'], $targetDocumentFromDB['ref']['data']);
 }
Example #17
0
 /**
  * Returns corresponding object indicated by MongoDBRef
  *
  * @param $fieldName
  * @return mixed
  * @throws InvalidReferenceException
  */
 public function readRef($fieldName)
 {
     $oRef = $this->readNestedAttribute($fieldName);
     if (!\MongoDBRef::isRef($oRef)) {
         throw new InvalidReferenceException();
     }
     if (isset($this->dbRefs) && isset($this->dbRefs[$fieldName])) {
         $modelInstance = $this->instantiateModel($this->dbRefs[$fieldName]);
     } else {
         if ($this->getDI()->has('mongoMapper')) {
             $modelInstance = $this->getDI()->get('mongoMapper')->resolveModel($oRef['$ref']);
         } else {
             return $oRef;
         }
     }
     return forward_static_call(array($modelInstance, 'findById'), $oRef['$id']);
 }
Example #18
0
 public function createReferencedDocument($sourceDocument = null, $refIsFull = true)
 {
     $sourceCollection = $this->getSourceCollection();
     $sourceId = new \MongoId();
     $identity = ['_id' => $sourceId, 'data' => md5(rand(0, time()))];
     if (is_array($sourceDocument)) {
         $sourceDocument = array_merge($sourceDocument, $identity);
     } else {
         $sourceDocument = $identity;
     }
     $sourceCollection->save($sourceDocument);
     if ($refIsFull) {
         return [\MongoDBRef::create($sourceCollection->getName(), $sourceId, $sourceCollection->db), $sourceDocument];
     } else {
         return [\MongoDBRef::create($sourceCollection->getName(), $sourceId), $sourceDocument];
     }
 }
Example #19
0
 /**
  *  @depends testReferences
  */
 public function testDeferencing()
 {
     $d = new Model1();
     $d->where('a', 'barfoo');
     foreach ($d as $doc) {
         $this->assertTrue(isset($doc->next));
         $this->assertTrue(MongoDBRef::isRef($doc->next));
         $this->assertTrue(MongoDBRef::isRef($doc->nested[0]));
         $this->assertTrue(MongoDBRef::isRef($doc->nested[1]));
         $this->assertTrue(MongoDBRef::isRef($doc->query));
         /* Check dynamic references properties */
         $this->assertTrue(is_array($doc->query['dynamic']));
         $this->assertTrue(count($doc->query['dynamic']) > 0);
         /* Deference */
         $doc->doDeferencing();
         /* Test deferenced values */
         $this->assertTrue($doc->next instanceof Model1);
         $this->assertTrue($doc->nested[0] instanceof Model1);
         $this->assertTrue($doc->nested[1] instanceof Model1);
         $this->assertTrue(is_array($doc->query));
         $this->assertTrue($doc->query[0] instanceof Model1);
         /* Testing mongodb refs */
         $this->assertTrue(is_array($doc->mdbref));
         foreach ($doc->mdbref as $property => $value) {
             if ($property == '_id') {
                 $this->assertEquals($value, $doc->next->getID());
                 continue;
             } else {
                 $this->assertEquals($value, $doc->next->{$property});
                 continue;
             }
             $this->assertTrue(FALSE);
         }
         /* Testing Iteration in defered documents */
         /* They should fail because they are cloned */
         /* instances of a real document */
         try {
             $doc->next->next();
             $this->assertTrue(FALSE);
         } catch (ActiveMongo_Exception $e) {
             $this->assertTrue(TRUE);
         }
     }
 }
Example #20
0
 public function walk($record)
 {
     if (!$this->started) {
         $this->clear();
         $this->started = true;
     } else {
         throw new \RuntimeException('Reader was already started. To run new scan please invoke clear() method');
     }
     if (is_array($record)) {
         if (\MongoDBRef::isRef($record)) {
             $this->references['*'] = self::simplifyReference($record);
         }
         array_walk($record, $this);
     } elseif (is_object($record)) {
         $this->walk_object($record);
     } else {
         throw new \InvalidArgumentException('Record for scan must be an object or an array');
     }
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  *
  * @access protected
  */
 protected function setUp()
 {
     if (file_exists('tests/classic.jpg')) {
         unlink('tests/classic.jpg');
     }
     $db = $this->sharedFixture->selectDB('phpunit');
     $grid = $db->getGridFS('_files', '_chunks');
     $grid->drop();
     $files = $db->selectCollection('_files');
     $chunks = $db->selectCollection('_chunks');
     $chunk4 = array('cn' => 4, 'data' => new MongoBinData('xyz'));
     $chunks->insert($chunk4);
     $chunk3 = array('cn' => 3, 'data' => new MongoBinData('rst'), 'next' => MongoDBRef::create($chunks->getName(), $chunk4['_id']));
     $chunks->insert($chunk3);
     $chunk2 = array('cn' => 2, 'data' => new MongoBinData('lmno'), 'next' => MongoDBRef::create($chunks->getName(), $chunk3['_id']));
     $chunks->insert($chunk2);
     $chunk1 = array('cn' => 1, 'data' => new MongoBinData('abc'), 'next' => MongoDBRef::create($chunks->getName(), $chunk2['_id']));
     $chunks->insert($chunk1);
     $files->insert(array("filename" => "classic.jpg", "contentType" => "image/jpeg", "length" => 4, "chunkSize" => 4, "next" => MongoDBRef::create($chunks->getName(), $chunk1['_id'])));
     $file = $grid->findOne();
     $this->object = new MongoGridFSFileClassic($file);
     $this->object->start = memory_get_usage(true);
 }
Example #22
0
 /**
  * method to load Mongo DB reference object
  * 
  * @param MongoDBRef $ref the reference object
  * 
  * @return array
  */
 public function getRef($ref)
 {
     if (!MongoDBRef::isRef($ref)) {
         return;
     }
     if (!$ref['$id'] instanceof MongoId) {
         $ref['$id'] = new MongoId($ref['$id']);
     }
     return new Mongodloid_Entity($this->_collection->getDBRef($ref));
 }
 /**
  * Utility function to expand any DBRefs present in a document
  * 
  * @param   mixed            The document to scan for DBRefs instances
  * @return  void
  * @access  private
  */
 private function _deref(&$data)
 {
     foreach ($data as $key => $value) {
         if (is_object($value) || is_array($value)) {
             if (is_object($data)) {
                 $data->{$key} = $this->_deref($value);
             } else {
                 $data[$key] = $this->_deref($value);
             }
         }
         if (MongoDBRef::isRef($value)) {
             if (is_object($data)) {
                 $data->{$key} = $this->_db->getDBRef($value);
             } else {
                 $data[$key] = $this->_db->getDBRef($value);
             }
         }
     }
     return $data;
 }
Example #24
0
<?php

// Helper functions and includs
include_once '/var/www/html/Lux/Core/Helper.php';
$db = new Db("Inventory");
$OUTPUT = new Output();
$REQUEST = new Request();
$collection = $db->selectCollection("Cart");
$RULES = new Rules(1, "cart");
$REQUEST = new Request();
// get the asset, push it into the cart that is selected
$collectionName = $REQUEST->get("collection", "Standard");
$cartName = $REQUEST->get("wishlist", "Default");
$document = $collection->findAndModify(array("user_id" => $RULES->getId()), array('$push' => array("wishlist." . $cartName => MongoDBRef::create($collectionName, $REQUEST->get("id"), "Assets"))));
// Used for analytics
$LOG = new Logging("Cart.order");
$LOG->log($RULES->getId(), 43, $REQUEST->get("id"), 100, "User Wished for item");
$OUTPUT->success(0, $document, null);
    public function testIsRef() {
        $this->assertFalse(MongoDBRef::isRef(array()));
        $this->assertFalse(MongoDBRef::isRef(array('$ns' => 'foo', '$id' => 'bar')));
        $ref = $this->object->createDBRef('foo.bar', array('foo' => 'bar'));
        $this->assertEquals(NULL, $ref);

        $ref = array('$ref' => 'blog.posts', '$id' => new MongoId('cb37544b9dc71e4ac3116c00'));
        $this->assertTrue(MongoDBRef::isRef($ref));
    }
Example #26
0
 /**
  * Test ExtReference::closureToPHP()
  *
  * @return void
  */
 public function testClosureToPHP()
 {
     $this->assertEqualsClosure(ExtReference::create(__METHOD__, __FILE__), \MongoDBRef::create(__METHOD__, __FILE__), $this->type->closureToPHP());
     $this->assertEqualsClosure(null, null, $this->type->closureToPHP());
 }
 /**
  *	--------------------------------------------------------------------------------
  *	Create Database Reference
  *	--------------------------------------------------------------------------------
  *
  *	Create mongo dbref object to store later
  *
  *	@usage : $ref = $this->mongo_db->create_dbref($collection, $id);
  */
 public function create_dbref($collection = "", $id = "", $database = FALSE)
 {
     if (empty($collection)) {
         show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
     }
     if (empty($id) or !isset($id)) {
         show_error('To use MongoDBRef::create() ala create_dbref() you must pass a valid id field of the object which to link', 500);
     }
     $db = $database ? $database : $this->db;
     if ($this->CI->config->item('mongo_return') == 'object') {
         return (object) MongoDBRef::create($collection, $id, $db);
     } else {
         return (array) MongoDBRef::create($collection, $id, $db);
     }
 }
Example #28
0
 public function get()
 {
     if (func_num_args() == 0) {
         return $this->_values;
     }
     $key = func_get_arg(0);
     if ($key == '_id') {
         return $this->getId();
     }
     $getRef = func_num_args() > 1 ? func_get_arg(1) : false;
     $key = preg_replace('@\\[([^\\]]+)\\]@', '.$1', $key);
     $result = $this->_values;
     // if this is chained key, let's pull it
     if (strpos($key, '.') !== FALSE) {
         do {
             list($current, $key) = explode('.', $key, 2);
             if (isset($result[$current])) {
                 $result = $result[$current];
             } else {
                 // if key is not in the values, let's return null -> not found key
                 return null;
             }
         } while (strpos($key, '.') !== FALSE);
     }
     if (!isset($result[$key])) {
         return null;
     }
     if (!$getRef) {
         //lazy load MongoId Ref objects or MongoDBRef
         //http://docs.mongodb.org/manual/reference/database-references/
         if ($result[$key] instanceof MongoId && $this->collection()) {
             $result[$key] = $this->collection()->findOne($result[$key]['$id']);
         } else {
             if (MongoDBRef::isRef($result[$key])) {
                 $result[$key] = $this->loadRef($result[$key]);
             }
         }
     }
     return $result[$key];
 }
Example #29
0
 /**
  * Convert data changes into operations
  * 
  * @param array $data
  */
 public function processChanges(array $data = array())
 {
     foreach ($data as $property => $value) {
         if ($property === '_id') {
             continue;
         }
         if (!array_key_exists($property, $this->_cleanData)) {
             $this->addOperation('$set', $property, $value);
             continue;
         }
         $newValue = $value;
         $oldValue = $this->_cleanData[$property];
         if (MongoDBRef::isRef($newValue) && MongoDBRef::isRef($oldValue)) {
             $newValue['$id'] = $newValue['$id']->__toString();
             $oldValue['$id'] = $oldValue['$id']->__toString();
         }
         if ($newValue !== $oldValue) {
             $this->addOperation('$set', $property, $value);
         }
     }
     foreach ($this->_cleanData as $property => $value) {
         if (array_key_exists($property, $data)) {
             continue;
         }
         $this->addOperation('$unset', $property, 1);
     }
 }
 /**
  * Creates a database reference
  *
  * @link http://www.php.net/manual/en/mongocollection.createdbref.php
  * @param array|object $document_or_id Object to which to create a reference.
  * @return array Returns a database reference array.
  */
 public function createDBRef($document_or_id)
 {
     if ($document_or_id instanceof \MongoId) {
         $id = $document_or_id;
     } elseif (is_object($document_or_id)) {
         if (!isset($document_or_id->_id)) {
             return null;
         }
         $id = $document_or_id->_id;
     } elseif (is_array($document_or_id)) {
         if (!isset($document_or_id['_id'])) {
             return null;
         }
         $id = $document_or_id['_id'];
     } else {
         $id = $document_or_id;
     }
     return MongoDBRef::create($this->name, $id);
 }