get() публичный статический Метод

Fetches the object pointed to by a reference
public static get ( MongoDB $db, array $ref ) : array | null
$db MongoDB Database to use
$ref array Reference to fetch
Результат array | null Returns the document to which the reference refers or null if the document does not exist (the reference is broken)
Пример #1
0
 public function validate($contentId, $text, $creating = true)
 {
     $valid = false;
     foreach ($this->commentableCollections as $collection) {
         $ref = MongoDBRef::create($collection, $this->_toMongoId($contentId));
         $result = MongoDBRef::get($this->mongo, $ref);
         if ($result != null) {
             $valid = true;
             break;
         }
     }
     if (!$valid) {
         return 'Invalid content id.';
     }
     $ref = MongoDBRef::create('users', Session::getVar('_id'));
     $text = substr($this->clean(preg_replace('/\\s{6,}/', "\n\n", preg_replace('/[[:blank:]]+/', ' ', $text))), 0, 1000);
     if (empty($text)) {
         return 'Invalid comment.';
     }
     $entry = array('contentId' => (string) $contentId, 'date' => time(), 'text' => $text, 'user' => $ref, 'ghosted' => false);
     if (!$creating) {
         unset($entry['contentId'], $entry['date'], $entry['user'], $entry['ghosted']);
     }
     self::ApcPurge('getForId', $contentId);
     return $entry;
 }
Пример #2
0
 private function resolveNotes($user)
 {
     if (empty($user['notes'])) {
         return $user;
     }
     foreach ($user['notes'] as $k => $note) {
         $user['notes'][$k]['user'] = MongoDBRef::get($this->mongo, $user['notes'][$k]['user']);
     }
     return $user;
 }
Пример #3
0
 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));
 }
 public function testGet()
 {
     $this->object->db->selectCollection("d")->insert(array("_id" => 123, "greeting" => "hi"));
     $this->sharedFixture->selectCollection("phpunit_temp", "d")->insert(array("_id" => 123, "greeting" => "bye"));
     $x = MongoDBRef::get($this->object->db, array('$ref' => "d", '$id' => 123));
     $this->assertNotNull($x);
     $this->assertEquals("hi", $x['greeting'], json_encode($x));
     $x = MongoDBRef::get($this->object->db, array('$ref' => "d", '$id' => 123, '$db' => 'phpunit_temp'));
     $this->assertNotNull($x);
     $this->assertEquals("bye", $x['greeting'], json_encode($x));
 }
Пример #5
0
 public function testGetDBRef()
 {
     $db = $this->sharedFixture->selectDB("foo");
     $c = $db->selectCollection("bar");
     $obj = array("uid" => 0);
     $c->insert($obj);
     $ref = $c->createDBRef($obj);
     $mem = memory_get_usage(true);
     for ($i = 0; $i < 10000; $i++) {
         MongoDBRef::get($db, $ref);
     }
     $this->assertEquals($mem, memory_get_usage(true));
 }
 public function testGet()
 {
     $this->object->db->d->insert(array("_id" => 123, "greeting" => "hi"));
     $m = new Mongo();
     $c = $m->phpunit_temp->d;
     $c->drop();
     $c->insert(array("_id" => 123, "greeting" => "bye"), true);
     $x = MongoDBRef::get($this->object->db, array('$ref' => "d", '$id' => 123));
     $this->assertNotNull($x);
     $this->assertEquals("hi", $x['greeting'], json_encode($x));
     $x = MongoDBRef::get($this->object->db, array('$ref' => "d", '$id' => 123, '$db' => 'phpunit_temp'));
     $this->assertNotNull($x);
     $this->assertEquals("bye", $x['greeting'], json_encode($x));
 }
Пример #7
0
 /**
  * @param mixed $reference Reference to populate
  * @param null|string $cname Class of model to populate. If not specified, populates data on current model
  * @return EMongoModel
  */
 public function populateReference($reference, $cname = null)
 {
     $row = MongoDBRef::get(self::$db->getDB(), $reference);
     $o = is_null($cname) ? $this : $cname::model();
     return $o->populateRecord($row);
 }
Пример #8
0
 /**
  *  Perform a deferencing in the current document, if there is
  *  any reference.
  *
  *  ActiveMongo will do its best to group references queries as much 
  *  as possible, in order to perform as less request as possible.
  *
  *  ActiveMongo doesn't rely on MongoDB references, but it can support 
  *  it, but it is prefered to use our referencing.
  *
  *  @experimental
  */
 final function doDeferencing($refs = array())
 {
     /* Get current document */
     $document = get_document_vars($this);
     if (count($refs) == 0) {
         /* Inspect the whole document */
         $this->getDocumentReferences($document, $refs);
     }
     $db = $this->_getConnection();
     /* Gather information about ActiveMongo Objects
      * that we need to create
      */
     $classes = array();
     foreach ($refs as $ref) {
         if (!isset($ref['ref']['class'])) {
             /* Support MongoDBRef, we do our best to be compatible {{{ */
             /* MongoDB 'normal' reference */
             $obj = MongoDBRef::get($db, $ref['ref']);
             /* Offset the current document to the right spot */
             /* Very inefficient, never use it, instead use ActiveMongo References */
             $this->_deferencingRestoreProperty($document, $ref['key'], $obj);
             /* Dirty hack, override our current document 
              * property with the value itself, in order to
              * avoid replace a MongoDB reference by its content
              */
             $this->_deferencingRestoreProperty($this->_current, $ref['key'], $obj);
             /* }}} */
         } else {
             if (isset($ref['ref']['dynamic'])) {
                 /* ActiveMongo Dynamic Reference */
                 /* Create ActiveMongo object */
                 $req = $this->_deferencingCreateObject($ref['ref']['class']);
                 /* Restore saved query */
                 $req->_deferencingQuery($ref['ref']['dynamic']);
                 $results = array();
                 /* Add the result set */
                 foreach ($req as $result) {
                     $results[] = clone $result;
                 }
                 /* add  information about the current reference */
                 foreach ($ref['ref'] as $key => $value) {
                     $results[$key] = $value;
                 }
                 $this->_deferencingRestoreProperty($document, $ref['key'], $results);
             } else {
                 /* ActiveMongo Reference FTW! */
                 $classes[$ref['ref']['class']][] = $ref;
             }
         }
     }
     /* {{{ Create needed objects to query MongoDB and replace
      * our references by its objects documents. 
      */
     foreach ($classes as $class => $refs) {
         $req = $this->_deferencingCreateObject($class);
         /* Load list of IDs */
         $ids = array();
         foreach ($refs as $ref) {
             $ids[] = $ref['ref']['$id'];
         }
         /* Search to MongoDB once for all IDs found */
         $req->find($ids);
         /* Replace our references by its objects */
         foreach ($refs as $ref) {
             $id = $ref['ref']['$id'];
             $place = $ref['key'];
             foreach ($req as $item) {
                 if ($item->getID() == $id) {
                     $this->_deferencingRestoreProperty($document, $place, clone $req);
                 }
             }
             unset($obj);
         }
         /* Release request, remember we
          * safely cloned it,
          */
         unset($req);
     }
     // }}}
     /* Replace the current document by the new deferenced objects */
     foreach ($document as $key => $value) {
         $this->{$key} = $value;
     }
 }
Пример #9
0
 /**
  * Resolves user references.
  * 
  * @param array &$user User reference.
  */
 public function resolveUser(&$user)
 {
     if (isset($user['$id']) && !$user['$id']) {
         $user = array('username' => 'Anonymous');
     } else {
         if (is_string($user)) {
             $user = array('username' => $user);
         } else {
             $user = MongoDBRef::get($this->mongo, $user);
         }
     }
     if (empty($user)) {
         $user = array('username' => 'Unknown');
     }
 }
Пример #10
0
 /**
  * Get database reference
  *
  * Get mongo object from database reference using MongoDBRef
  *
  * <code>
  * $this->mongo_db->get_dbref($object);
  * </code>
  *
  * @param object $object A dbref object
  *
  * @access public
  * @return array|object
  */
 public function get_dbref($object)
 {
     if (empty($object) || !isset($object)) {
         $this->_show_error('To use MongoDBRef::get() ala get_dbref() you must pass a valid reference object', 500);
     }
     return MongoDBRef::get($this->_dbhandle, $object);
 }
Пример #11
0
 /**
  * Fetches the document pointed to by a database reference
  *
  * @link http://www.php.net/manual/en/mongodb.getdbref.php
  * @param array $ref A database reference.
  * @return array Returns the document pointed to by the reference.
  */
 public function getDBRef(array $ref)
 {
     return MongoDBRef::get($this, $ref);
 }
Пример #12
0
 public function testGetWithInvalidRef()
 {
     $db = $this->getDatabase();
     $this->assertNull(\MongoDBRef::get($db, []));
 }
Пример #13
0
 protected function loadAssociation($kind, $attrName, array $options)
 {
     if (!isset($options['className'])) {
         $remoteClass = $this->resolveAssociationClass($attrName);
     } else {
         $remoteClass = $options['className'];
     }
     $infl = self::services()->get('inflector');
     $foreignKey = $infl->singularize(static::tableName()) . '_id';
     switch ($kind) {
         case 'hasMany':
             if (isset($this->attributes[$attrName]) && is_array($this->attributes[$attrName])) {
                 /**
                  * If the attribute is present and it is an array, it is assumed
                  * it's an array of references.
                  * Missing records are ignored.
                  */
                 $assoc = new \Rails\ActiveRecord\Collection();
                 foreach ($this->attributes[$attrName] as $ref) {
                     if ($record = $remoteClass::where(['_id' => (int) $ref['$id']])->first()) {
                         $assoc[] = $record;
                     }
                 }
             } else {
                 /**
                  * Fetch the models from the associated collection.
                  * Note that the documents must have a {referenced_table_name}_id
                  * key (like "user_id") holding a reference to this record.
                  */
                 $assoc = $remoteClass::where([$infl->singularize(static::tableName()) . '.$id' => $this->id()]);
             }
             break;
         case 'belongsTo':
             if (!isset($this->attributes[$attrName])) {
                 return null;
             } elseif (!is_array($this->attributes[$attrName])) {
                 throw new Exception\InvalidArgumentException(sprintf("Belongs-to attribute value %s::\$%s must be MongoDBRef (array), %s passed", get_called_class(), $attrName, gettype($attrName)));
             }
             $refData = \MongoDBRef::get(static::connection()->database(), $this->attributes[$attrName]);
             if ($refData) {
                 $assoc = new $remoteClass($refData);
                 $assoc->isNewRecord = false;
             }
             break;
     }
     return $assoc;
 }
Пример #14
0
 /**
  *	--------------------------------------------------------------------------------
  *	Get Database Reference
  *	--------------------------------------------------------------------------------
  *
  *	Get mongo object from database reference using MongoDBRef
  *
  *	@usage : $this->mongo_db->get_dbref($object);
  */
 public function get_dbref($obj)
 {
     if (empty($obj) or !isset($obj)) {
         show_error('To use MongoDBRef::get() ala get_dbref() you must pass a valid reference object', 500);
     }
     if ($this->CI->config->item('mongo_return') == 'object') {
         return (object) MongoDBRef::get($this->db, $obj);
     } else {
         return (array) MongoDBRef::get($this->db, $obj);
     }
 }
Пример #15
0
 /**
  * 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;
 }
Пример #16
0
 public function doc($key, $data = null)
 {
     if (array_key_exists($key, $this->_data)) {
         return $this->_data[$key]->extend($data);
     }
     if (!is_array($data)) {
         $data = array();
     }
     $set = $this->hasRequirement($key, 'set');
     $doc = $this->hasRequirement($key, 'doc');
     $ref = MongoDbRef::isRef($data);
     $config = array();
     if ($ref) {
         $config['collection'] = $data['$ref'];
         $config['isReference'] = true;
         $data = MongoDBRef::get($this->getSchema()->getMongoDB(), $data);
         // If this is a broken reference then no point keeping it for later
         if (!$data) {
             if ($this->hasRequirement($key, 'auto')) {
                 $data = array();
             } else {
                 return $this->_data[$key] = null;
             }
         }
     }
     if (!($doc || $set)) {
         $set = $this->_dataIsSimpleArray($data);
     }
     $schemaType = $set ? 'set' : 'doc';
     if ($documentClass = $this->getRequirement($key, $schemaType)) {
         $schemaType .= ":" . $documentClass;
     }
     $doc = $this->getSchema()->resolve($schemaType, $data, $config);
     $this->setProperty($key, $doc);
     return $doc;
 }
Пример #17
0
<?php

class MyDB extends MongoDB
{
    public function __construct()
    {
    }
}
$db = new MyDB();
try {
    MongoDBRef::get($db, array('$ref' => "", '$id' => 1));
} catch (MongoException $e) {
    var_dump($e->getCode());
    var_dump($e->getMessage());
}
Пример #18
0
 public function testGetWithInvalidRef()
 {
     $client = new \MongoClient();
     $db = $client->selectDB('mongo-php-adapter');
     $this->assertNull(\MongoDBRef::get($db, []));
 }
 /**
  *	--------------------------------------------------------------------------------
  *	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::get($this->db, $obj);
     }
 }
Пример #20
0
 public static function getObject($ref)
 {
     $obj = $ref;
     if (MongoDBRef::isRef($ref)) {
         $cls = self::getResource()->getClass($ref['$ref']);
         if (!class_exists($cls)) {
             throw new ZFE_Model_Mongo_Exception("There is no model for the referred entity '" . $ref['$ref'] . "'.\n                    Consider creating {$cls} or add a class mapping in resources.mongo.mapping[].");
         }
         $obj = MongoDBRef::get(static::getDatabase(), $ref);
         $obj = is_null($obj) ? $obj : $cls::map($obj);
     }
     return $obj;
 }
Пример #21
0
 /**
  * Get a property
  * 
  * @param mixed $property
  */
 public function getProperty($property)
 {
     // If property exists and initialised then return it
     if (array_key_exists($property, $this->_data)) {
         return $this->_data[$property];
     }
     // Fetch clean data for this property
     if (array_key_exists($property, $this->_cleanData)) {
         $data = $this->_cleanData[$property];
     } else {
         $data = array();
     }
     // If data is not an array then we can do nothing else with it
     if (!is_array($data)) {
         $this->_data[$property] = $data;
         return $this->_data[$property];
     }
     // If property is supposed to be an array then initialise an array
     if ($this->hasRequirement($property, 'Array')) {
         return $this->_data[$property] = $data;
     }
     // If property is a reference to another document then fetch the reference document
     $db = $this->getConfigAttribute('db');
     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[$property] = null;
             return $this->_data[$property];
         }
         $reference = true;
     } else {
         $collection = $this->getConfigAttribute('collection');
         $reference = false;
     }
     // Find out the class name of the document or document set we are loaded
     if ($className = $this->hasRequirement($property, 'DocumentSet')) {
         $docType = 'Shanty_Mongo_DocumentSet';
     } else {
         $className = $this->hasRequirement($property, 'Document');
         // Load a document anyway so long as $data is not empty
         if (!$className && !empty($data)) {
             $className = 'Shanty_Mongo_Document';
         }
         if ($className) {
             $docType = 'Shanty_Mongo_Document';
         }
     }
     // Nothing else to do
     if (!$className) {
         return null;
     }
     // Configure property for document/documentSet usage
     $config = array();
     $config['new'] = empty($data);
     $config['connectionGroup'] = $this->getConfigAttribute('connectionGroup');
     $config['db'] = $this->getConfigAttribute('db');
     $config['collection'] = $collection;
     $config['requirementModifiers'] = $this->getRequirements($property . '.');
     $config['hasId'] = $this->hasRequirement($property, 'hasId');
     $config['parent'] = $this;
     // keep track of hierarchy
     if (!$reference) {
         $config['pathToDocument'] = $this->getPathToProperty($property);
         $config['criteria'] = $this->getCriteria();
     }
     // Initialise document
     $document = new $className($data, $config);
     // if this document was a reference then remember that
     if ($reference) {
         $this->_references->attach($document);
     }
     $this->_data[$property] = $document;
     return $this->_data[$property];
 }
Пример #22
0
 /**
  * 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);
 }