本文整理汇总了PHP中MongoDBRef::isRef方法的典型用法代码示例。如果您正苦于以下问题:PHP MongoDBRef::isRef方法的具体用法?PHP MongoDBRef::isRef怎么用?PHP MongoDBRef::isRef使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MongoDBRef
的用法示例。
在下文中一共展示了MongoDBRef::isRef方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testShouldReturnLazyLoadingCursor
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)));
}
}
示例2: isRef
/**
* 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);
}
示例3: __get
/**
* 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);
}
示例4: update
/**
* 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);
}
示例5: __construct
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;
}
示例6: testExtendedDBRef
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']);
}
示例7: readRef
/**
* 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']);
}
示例8: testDeferencing
/**
* @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);
}
}
}
示例9: walk
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');
}
}
示例10: getRelated
/**
* 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;
}
示例11: getProperty
/**
* 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;
}
示例12: getRelated
/**
* 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
}
示例13: findReferences
/**
* 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);
}
示例14: normalizeDocument
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;
}
示例15: _internalValue
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;
}