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))); } }
/** * 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); }
/** * If the accessed data entry is a MongoDB reference, fetch the * reference data and turn it into an object of the reference data * class. * * By default, it will create an object with the class name based on the * reference collection, but if it is mentioned in the mapping configuration, * it will use the mapping's setting instead. If the class does not exist, * an explanatory exception will be thrown. * * Other conversions: MongoDate to DateTime */ public function __get($key) { if (!isset($this->_data[$key])) { return null; } if (MongoDBRef::isRef($this->_data[$key])) { if (isset($this->_refCache[$key])) { return $this->_refCache[$key]; } $resource = ZFE_Model_Mongo::getResource(); $ref = $this->_data[$key]['$ref']; $cls = $resource->getClass($ref); if (!class_exists($cls)) { throw new ZFE_Model_Mongo_Exception("There is no model for the referred entity '" . $ref . "'.\n Consider creating {$cls} or add a class mapping in resources.mongo.mapping[]."); } $val = $cls::map(MongoDBRef::get(self::getDatabase(), $this->_data[$key])); $this->_refCache[$key] = $val; return $val; } if ($this->_data[$key] instanceof MongoDate) { $val = new DateTime('@' . $this->_data[$key]->sec); $val->setTimeZone(new DateTimeZone(date_default_timezone_get())); return $val; } return parent::__get($key); }
/** * 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); }
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; }
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']); }
/** * 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']); }
/** * @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); } } }
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'); } }
/** * Returns the related record(s). * This method will return the related record(s) of the current record. * If the relation is 'one' it will return a single object * or null if the object does not exist. * If the relation is 'many' it will return an array of objects * or an empty iterator. * @param string $name the relation name (see {@link relations}) * @param boolean $refresh whether to reload the related objects from database. Defaults to false. * @param mixed $params array with additional parameters that customize the query conditions as specified in the relation declaration. * @return mixed the related object(s). * @throws EMongoException if the relation is not specified in {@link relations}. */ public function getRelated($name, $refresh = false, $params = array()) { if (!$refresh && $params === array() && (isset($this->_related[$name]) || array_key_exists($name, $this->_related))) { return $this->_related[$name]; } $relations = $this->relations(); if (!isset($relations[$name])) { throw new EMongoException(Yii::t('yii', '{class} does not have relation "{name}".', array('{class}' => get_class($this), '{name}' => $name))); } Yii::trace('lazy loading ' . get_class($this) . '.' . $name, 'extensions.MongoYii.EMongoModel'); // I am unsure as to the purpose of this bit //if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation)) //return $relation instanceof CHasOneRelation ? null : array(); $cursor = array(); $relation = $relations[$name]; // Let's get the parts of the relation to understand it entirety of its context $cname = $relation[1]; $fkey = $relation[2]; $pk = isset($relation['on']) ? $this->{$relation['on']} : $this->{$this->primaryKey()}; // Form the where clause $where = array(); if (isset($relation['where'])) { $where = array_merge($relation['where'], $params); } // Find out what the pk is and what kind of condition I should apply to it if (is_array($pk)) { //It is an array of references if (MongoDBRef::isRef(reset($pk))) { $result = array(); foreach ($pk as $singleReference) { $row = $this->populateReference($singleReference, $cname); if ($row) { array_push($result, $row); } } return $result; } // It is an array of _ids $clause = array_merge($where, array($fkey => array('$in' => $pk))); } elseif ($pk instanceof MongoDBRef) { // I should probably just return it here // otherwise I will continue on return $this->populateReference($pk, $cname); } else { // It is just one _id $clause = array_merge($where, array($fkey => $pk)); } $o = $cname::model(); if ($relation[0] === 'one') { // Lets find it and return it $cursor = $o->findOne($clause); } elseif ($relation[0] === 'many') { // Lets find them and return them $cursor = $o->find($clause); } return $cursor; }
/** * Get a property * * @param mixed $property */ public function getProperty($index = null) { $new = is_null($index); // If property exists and initialised then return it if (!$new && array_key_exists($index, $this->_data)) { return $this->_data[$index]; } // Make sure we are not trying to create a document that is supposed to be saved as a reference if ($new && $this->hasRequirement(static::DYNAMIC_INDEX, 'AsReference')) { require_once 'Shanty/Mongo/Exception.php'; throw new Shanty_Mongo_Exception("Can not create a new document from documentset where document must be saved as a reference"); } if (!$new) { // Fetch clean data for this property if it exists if (array_key_exists($index, $this->_cleanData)) { $data = $this->_cleanData[$index]; } else { return null; } } else { $data = array(); } // If property is a reference to another document then fetch the reference document if (MongoDBRef::isRef($data)) { $collection = $data['$ref']; $data = MongoDBRef::get($this->_getMongoDB(false), $data); // If this is a broken reference then no point keeping it for later if (!$data) { $this->_data[$index] = null; return $this->_data[$index]; } $reference = true; } else { $reference = false; $collection = $this->getConfigAttribute('collection'); } $config = array(); $config['new'] = $new; $config['requirementModifiers'] = $this->getRequirements(self::DYNAMIC_INDEX . '.'); $config['parentIsDocumentSet'] = true; $config['connectionGroup'] = $this->getConfigAttribute('connectionGroup'); $config['db'] = $this->getConfigAttribute('db'); $config['collection'] = $collection; $config['parent'] = $this; // keep track of hierarchy if (!$reference) { // If this is a new array element. We will $push to the array when saving if ($new) { $path = $this->getPathToDocument(); } else { $path = $this->getPathToProperty($index); } $config['pathToDocument'] = $path; $config['criteria'] = $this->getCriteria(); $config['hasId'] = $this->hasRequirement(self::DYNAMIC_INDEX, 'hasId'); } // get the document class $documentClass = $this->hasRequirement(self::DYNAMIC_INDEX, 'Document'); if (isset($data['_type']) && !empty($data['_type'][0])) { $documentClass = $data['_type'][0]; } $document = new $documentClass($data, $config); // if this document was a reference then remember that if ($reference) { $this->_references->attach($document); } // If this is not a new document cache it if (!$new) { $this->_data[$index] = $document; } return $document; }
/** * Returns the related record(s). * This method will return the related record(s) of the current record. * If the relation is 'one' it will return a single object * or null if the object does not exist. * If the relation is 'many' it will return an array of objects * or an empty iterator. * @param string $name the relation name (see {@link relations}) * @param boolean $refresh whether to reload the related objects from database. Defaults to false. * @param mixed $params array with additional parameters that customize the query conditions as specified in the relation declaration. * @return mixed the related object(s). * @throws EMongoException if the relation is not specified in {@link relations}. */ public function getRelated($name, $refresh = false, $params = array()) { if (!$refresh && $params === array() && (isset($this->_related[$name]) || array_key_exists($name, $this->_related))) { return $this->_related[$name]; } $relations = $this->relations(); if (!isset($relations[$name])) { throw new EMongoException(Yii::t('yii', '{class} does not have relation "{name}".', array('{class}' => get_class($this), '{name}' => $name))); } Yii::trace('lazy loading ' . get_class($this) . '.' . $name, 'extensions.MongoYii.EMongoModel'); $cursor = array(); $relation = $relations[$name]; // Let's get the parts of the relation to understand it entirety of its context $cname = $relation[1]; $fkey = $relation[2]; $pk = isset($relation['on']) ? $this->{$relation['on']} : $this->getPrimaryKey(); // This takes care of cases where the PK is an DBRef and only one DBRef, where it could // be mistaken as a multikey field if ($relation[0] === 'one' && is_array($pk) && array_key_exists('$ref', $pk)) { $pk = array($pk); } // Form the where clause $where = $params; if (isset($relation['where']) && !$params) { $where = array_merge($relation['where'], $params); } // Find out what the pk is and what kind of condition I should apply to it if (is_array($pk)) { //It is an array of references if (MongoDBRef::isRef(reset($pk))) { $result = array(); foreach ($pk as $singleReference) { $row = $this->populateReference($singleReference, $cname); // When $row does not exists it will return null. It will not add it to $result array_push($result, $row); } // When $row is null count($result) will be 0 and $result will be an empty array // Because we are a one relation we want to return null when a row does not exists // Currently it was returning an empty array if ($relation[0] === 'one' && count($result) > 0) { $result = $result[0]; } return $this->_related[$name] = $result; } // It is an array of _ids $clause = array_merge($where, array($fkey => array('$in' => $pk))); } elseif ($pk instanceof MongoDBRef) { // I should probably just return it here // otherwise I will continue on return $this->_related[$name] = $this->populateReference($pk, $cname); } else { // It is just one _id $clause = array_merge($where, array($fkey => $pk)); } $o = $cname::model($cname); if ($relation[0] === 'one') { // Lets find it and return it return $this->_related[$name] = $o->findOne($clause); } elseif ($relation[0] === 'many') { // Lets find them and return them $cursor = $o->find($clause)->sort(isset($relation['sort']) ? $relation['sort'] : array())->skip(isset($relation['skip']) ? $relation['skip'] : null)->limit(isset($relation['limit']) ? $relation['limit'] : null); if (!isset($relation['cache']) || $relation['cache'] === true) { return $this->_related[$name] = iterator_to_array($cursor); } } return $cursor; // FAIL SAFE }
/** * Check if in the current document to insert or update * exists any references to other ActiveMongo Objects. * * @return void */ final function findReferences(&$document) { if (!is_array($document)) { return; } foreach ($document as &$value) { $parent_class = __CLASS__; if (is_array($value)) { if (MongoDBRef::isRef($value)) { /* If the property we're inspecting is a reference, * we need to remove the values, restoring the valid * Reference. */ $arr = array('$ref' => 1, '$id' => 1, '$db' => 1, 'class' => 1, 'dynamic' => 1); foreach (array_keys($value) as $key) { if (!isset($arr[$key])) { unset($value[$key]); } } } else { $this->findReferences($value); } } else { if ($value instanceof $parent_class) { $value = $value->getReference(); } } } /* trick: delete last var. reference */ unset($value); }
private function normalizeDocument($document) { $document['id'] = (string) $document['_id']; foreach ($document['data'] as $key => $value) { // External content if (isset($value['ref']) && \MongoDBRef::isRef($value['ref'])) { $document['data'][$key] = $this->normalizeRef($value); } elseif (is_array($value) && isset($value['id_structure']) && $value['id_structure'] === self::STRUCTURE_TYPE_COLLECTION) { // Atention: $value for simple relation it is also an array $normalizedRef = array(); foreach ($value['ref'] as $collectionValue) { $normalizedRef[] = $this->normalizeRef($collectionValue); } $document['data'][$key] = $normalizedRef; // TODO instance } } unset($document['_id']); return $document; }
private function _internalValue($name, $value, $type = null) { if ('_id' === $name) { // \MongoId if (!$value instanceof \MongoId) { return new \MongoId($value); } else { return $value; } } if (null != $type) { $valueType = $type['type']; if ('string' == $valueType) { $value = \strval($value); } elseif ('boolean' == $valueType || 'bool' == $valueType) { $value = !!$value; } elseif ('integer' == $valueType || 'int' == $valueType) { $value = \intval($value); } elseif ('float' == $valueType || 'double' == $valueType) { $value = \doubleval($value); } elseif ('timestamp' == $valueType) { // MongoTimestamp is used by sharding. // If you're not looking to write sharding tools, what you probably want is MongoDate. if (!$value instanceof \MongoTimestamp) { $value = new \MongoTimestamp($value); } } elseif ('datetime' == $valueType || 'time' == $valueType || 'date' == $valueType) { if (!$value instanceof \MongoDate) { $value = new \MongoDate($value); // FIXME parse float into usec } } elseif (\is_array($value)) { // check if is ref if (\MongoDBRef::isRef($value)) { // which class?? } } } $value = $this->processValue($name, $value); return $value; }
public function testExportReferences() { // Pull all reference doc foreach ($this->_bob->friends as $friend) { } // Bob is going to become a friend of himself $this->_bob->friends[] = $this->_bob; $exportData = $this->_bob->friends->export(); $this->assertEquals(3, count($exportData)); $this->assertTrue(MongoDBRef::isRef($exportData[0])); $this->assertEquals('4c04516f1f5f5e21361e3ab1', $exportData[0]['$id']->__toString()); $this->assertTrue(MongoDBRef::isRef($exportData[1])); $this->assertEquals('4c0451791f5f5e21361e3ab2', $exportData[1]['$id']->__toString()); $this->assertTrue(MongoDBRef::isRef($exportData[2])); $this->assertEquals('4c04516a1f5f5e21361e3ab0', $exportData[2]['$id']->__toString()); }
/** * 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)); }
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)); }
/** * Will convert objects to arrays * @param int $deep How deep to recursively convert to arrays * @param mixed $values Used by the class when recursively converting arrays * @return array */ public function toArray($deep = 2, $values = null) { if (is_null($values)) { $values = $this->data; } // look for foreach ($values as $name => &$value) { if ($value instanceof \MongoId) { $value = $value->__toString(); } elseif ($value instanceof Mongo) { if ($deep > 0) { $value = $value->toArray($deep - 1); } else { $value = '...'; } } elseif (\MongoDBRef::isRef($value)) { if ($deep > 0) { $value = Connection::getInstance(self::$conn)->findOne($value['$ref'], array('_id' => $value['$id'])); } else { $value = '...'; } } elseif (is_array($value)) { $value = $this->toArray($deep, $value); } else { // run $value through get() as there may be some custom getter methods // as it may be a array or instances, we will skip if $name is not string if (is_string($name)) { $value = $this->get($name); } } } return $values; }
public static function isReference($value) { return \MongoDBRef::isRef($value); }
/** * Convert $query items for monog. Eg. convert {'key': [values]} to {'key': '$in': [values]} and * convert objects to their mongo ID * @param array $query ACQ mongo query to be converted * @return array $query PHP mongo ready query */ protected static function _convertQuery($query) { // Replace ZFE_Model_Mongo instances by their references $replaceWithReference = function (&$val) { $val = $val instanceof ZFE_Model_Mongo ? $val->getReference() : $val; }; array_walk($query, function (&$val, $key) use($replaceWithReference) { if ($key[0] == '$') { return; } // Special case to take MongoIds out of references if ($key == '_id' && is_array($val)) { // If it is a single reference, take out the ID and continue if (MongoDBRef::isRef($val)) { $val = $val['$id']; return; } // Create an $in operation with an array of IDs $val = array('$in' => array_map(function ($ref) { return MongoDBRef::isRef($ref) ? $ref['$id'] : $ref; }, $val)); return; } if (is_array($val)) { $keys = array_keys($val); $mongoOperators = array_reduce($keys, function ($u, $v) { return $u || $v[0] == '$'; }, false); if (!$mongoOperators) { array_walk($val, $replaceWithReference); // MB UPDATE: I think this has to be {'$in': ["en", "ja"... rather than {'$in': {"1":"ja","2":"fr",.. // which previously just '$in' => $val was creating, wrong array for $in // anyway, putting a note for now encase it breaks anything :) $val = array('$in' => array_values($val)); // $val = array('$in' => $val); } } else { $replaceWithReference($val); } }); return $query; }
/** * */ public function &__get($parameter) { // Return requested array if not a MongoDB reference if (array_key_exists($parameter, $this->__data) && is_array($this->__data[$parameter]) && !\MongoDBRef::isRef($this->__data[$parameter])) { // Save is needed $this->__saved = false; // Return array return $this->__data[$parameter]; } // MongoId is requested, but didn't exists if ('id' == $parameter && false == array_key_exists('_id', $this->__data)) { $value = $this->__set('_id', new \MongoId()); } elseif ('id' == $parameter) { $value = $this->__data['_id']; } elseif (array_key_exists($parameter, $this->__data)) { $value = $this->__data[$parameter]; } else { $value = null; } // Return a DataTime object instand of a MongoDate object if ($value instanceof \MongoDate) { $value = new \DateTime("@{$value->sec}"); $value->setTimezone($this->__timezone); } // Return model if value is database reference if (is_array($value) && \MongoDBRef::isRef($value)) { $value = $this->__data[$parameter] = Query::init($value['$ref'])->is('_id', new \MongoId($value['$id']))->findOne(); } // Return null if parameter has not been found return $value; }
/** * If the attribute of $key is a reference , * load its original record from db and save to $_cache temporarily. * * @param string $key key * * @return null */ protected function loadRef($key) { $attrs = $this->getAttrs(); $reference = $attrs[$key]; $cache =& $this->_cache; if (isset($this->cleanData[$key])) { $value = $this->cleanData[$key]; } else { $value = null; } $model = $reference['model']; $type = $reference['type']; if (isset($cache[$key])) { $obj =& $cache[$key]; return $obj; } else { if (class_exists($model)) { if ($type == self::DATA_TYPE_REFERENCE) { if (\MongoDBRef::isRef($value)) { $object = $model::id($value['$id']); $cache[$key] = $object; return $object; } return null; } elseif ($type == self::DATA_TYPE_REFERENCES) { $res = array(); if (!empty($value)) { foreach ($value as $item) { if (isset($item['$id'], $item['$ref'])) { $record = $model::id($item['$id']); if ($record) { $res[] = $record; } } } } $set = Collection::make($res); $cache[$key] = $set; $obj =& $cache[$key]; return $obj; } } } }
/** * @dataProvider dataIsRef */ public function testIsRef($expected, $ref) { $this->assertSame($expected, \MongoDBRef::isRef($ref)); }
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]; }
public function testCreateReference() { $reference = $this->_bob->createReference(); $this->assertTrue(MongoDBRef::isRef($reference)); $this->assertEquals('user', $reference['$ref']); $this->assertType(PHPUnit_Framework_Constraint_IsType::TYPE_OBJECT, $reference['$id']); $this->assertEquals('MongoId', get_class($reference['$id'])); $this->assertEquals('4c04516a1f5f5e21361e3ab0', $reference['$id']->__toString()); }
/** * 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; }
public function testIsRef() { $this->assertFalse(MongoDBRef::isRef((object)array())); $this->assertFalse(MongoDBRef::isRef((object)array('$ns' => 'foo', '$id' => 'bar'))); $ref = (object)array('$ref' => 'blog.posts', '$id' => new MongoId('cb37544b9dc71e4ac3116c00')); $this->assertTrue(MongoDBRef::isRef($ref)); }
/** * 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); } }
<?php var_dump(MongoDBRef::isRef(array('$ref' => 'dbref', '$id' => 123))); var_dump(MongoDBRef::isRef(array('$ref' => 'dbref', '$id' => new MongoId()))); var_dump(MongoDBRef::isRef(array('$ref' => 'dbref', '$id' => 123, '$db' => 'test'))); var_dump(MongoDBRef::isRef((object) array('$ref' => 'dbref', '$id' => 123))); var_dump(MongoDBRef::isRef((object) array('$ref' => 'dbref', '$id' => new MongoId()))); var_dump(MongoDBRef::isRef((object) array('$ref' => 'dbref', '$id' => 123, '$db' => 'test'))); var_dump(MongoDBRef::isRef(null)); var_dump(MongoDBRef::isRef(1)); var_dump(MongoDBRef::isRef(array())); var_dump(MongoDBRef::isRef(array('$ref' => 'dbref'))); var_dump(MongoDBRef::isRef(array('$id' => 123, '$db' => 'test'))); var_dump(MongoDBRef::isRef((object) array())); var_dump(MongoDBRef::isRef((object) array('$ref' => 'dbref'))); var_dump(MongoDBRef::isRef((object) array('$id' => 123, '$db' => 'test')));