3 +---------------------------------------------------------------------------------+
4 | Copyright (c) 2010 ActiveMongo |
5 +---------------------------------------------------------------------------------+
6 | Redistribution and use in source and binary forms, with or without |
7 | modification, are permitted provided that the following conditions are met: |
8 | 1. Redistributions of source code must retain the above copyright |
9 | notice, this list of conditions and the following disclaimer. |
11 | 2. Redistributions in binary form must reproduce the above copyright |
12 | notice, this list of conditions and the following disclaimer in the |
13 | documentation and/or other materials provided with the distribution. |
15 | 3. All advertising materials mentioning features or use of this software |
16 | must display the following acknowledgement: |
17 | This product includes software developed by César D. Rodas. |
19 | 4. Neither the name of the César D. Rodas nor the |
20 | names of its contributors may be used to endorse or promote products |
21 | derived from this software without specific prior written permission. |
23 | THIS SOFTWARE IS PROVIDED BY CÉSAR D. RODAS ''AS IS'' AND ANY |
24 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
25 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
26 | DISCLAIMED. IN NO EVENT SHALL CÉSAR D. RODAS BE LIABLE FOR ANY |
27 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
28 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
29 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
30 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
31 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
32 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE |
33 +---------------------------------------------------------------------------------+
34 | Authors: César Rodas <crodas@php.net> |
35 +---------------------------------------------------------------------------------+
38 // array get_document_vars(stdobj $obj) {{{
40 * Simple hack to avoid get private and protected variables
43 * @param bool $include_id
47 function get_document_vars($obj, $include_id=true)
49 $document = get_object_vars($obj);
50 if ($include_id && $obj->getID()) {
51 $document['_id'] = $obj->getID();
60 * Simple ActiveRecord pattern built on top of MongoDB. This class
61 * aims to provide easy iteration, data validation before update,
62 * and efficient update.
64 * @author César D. Rodas <crodas@php.net>
65 * @license PHP License
66 * @package ActiveMongo
70 abstract class ActiveMongo
implements Iterator
, Countable
, ArrayAccess
75 * Current databases objects
81 * Current collections objects
85 private static $_collections;
87 * Current connection to MongoDB
89 * @type MongoConnection
91 private static $_conn;
99 * List of events handlers
103 static private $_events = array();
105 * List of global events handlers
109 static private $_super_events = array();
115 private static $_host;
121 private $_current = array();
127 private $_cursor = null;
129 /* {{{ Silly but useful query abstraction */
130 private $_query = null;
131 private $_sort = null;
134 private $_properties = null;
138 * Current document ID
145 * Tell if the current object
150 private $_cloned = false;
153 // GET CONNECTION CONFIG {{{
155 // string getCollectionName() {{{
157 * Get Collection Name, by default the class name,
158 * but you it can be override at the class itself to give
161 * @return string Collection Name
163 protected function getCollectionName()
165 return strtolower(get_class($this));
169 // string getDatabaseName() {{{
171 * Get Database Name, by default it is used
172 * the db name set by ActiveMong::connect()
174 * @return string DB Name
176 protected function getDatabaseName()
178 if (is_null(self
::$_db)) {
179 throw new MongoException("There is no information about the default DB name");
185 // void install() {{{
189 * This static method iterate over the classes lists,
190 * and execute the setup() method on every ActiveMongo
191 * subclass. You should do this just once.
194 final public static function install()
196 $classes = array_reverse(get_declared_classes());
197 foreach ($classes as $class)
199 if ($class == __CLASS__
) {
202 if (is_subclass_of($class, __CLASS__
)) {
210 // void connection($db, $host) {{{
214 * This method setup parameters to connect to a MongoDB
215 * database. The connection is done when it is needed.
217 * @param string $db Database name
218 * @param string $host Host to connect
222 final public static function connect($db, $host='localhost')
224 self
::$_host = $host;
229 // MongoConnection _getConnection() {{{
233 * Get a valid database connection
235 * @return MongoConnection
237 final protected function _getConnection()
239 if (is_null(self
::$_conn)) {
240 if (is_null(self
::$_host)) {
241 self
::$_host = 'localhost';
243 self
::$_conn = new Mongo(self
::$_host);
245 $dbname = $this->getDatabaseName();
246 if (!isSet(self
::$_dbs[$dbname])) {
247 self
::$_dbs[$dbname] = self
::$_conn->selectDB($dbname);
249 return self
::$_dbs[$dbname];
253 // MongoCollection _getCollection() {{{
257 * Get a collection connection.
259 * @return MongoCollection
261 final protected function _getCollection()
263 $colName = $this->getCollectionName();
264 if (!isset(self
::$_collections[$colName])) {
265 self
::$_collections[$colName] = self
::_getConnection()->selectCollection($colName);
267 return self
::$_collections[$colName];
273 // GET DOCUMENT TO SAVE OR UPDATE {{{
275 // bool getCurrentSubDocument(array &$document, string $parent_key, array $values, array $past_values) {{{
277 * Generate Sub-document
279 * This method build the difference between the current sub-document,
280 * and the origin one. If there is no difference, it would do nothing,
281 * otherwise it would build a document containing the differences.
283 * @param array &$document Document target
284 * @param string $parent_key Parent key name
285 * @param array $values Current values
286 * @param array $past_values Original values
290 final function getCurrentSubDocument(&$document, $parent_key, Array $values, Array $past_values)
293 * The current property is a embedded-document,
294 * now we're looking for differences with the
295 * previous value (because we're on an update).
297 * It behaves exactly as getCurrentDocument,
298 * but this is simples (it doesn't support
301 foreach ($values as $key => $value) {
302 $super_key = "{$parent_key}.{$key}";
303 if (is_array($value)) {
305 * Inner document detected
307 if (!isset($past_values[$key]) ||
!is_array($past_values[$key])) {
309 * We're lucky, it is a new sub-document,
312 $document['$set'][$super_key] = $value;
315 * This is a document like this, we need
316 * to find out the differences to avoid
319 if (!$this->getCurrentSubDocument($document, $super_key, $value, $past_values[$key])) {
324 } else if (!isset($past_values[$key]) ||
$past_values[$key] != $value) {
325 $document['$set'][$super_key] = $value;
329 foreach (array_diff(array_keys($past_values), array_keys($values)) as $key) {
330 $super_key = "{$parent_key}.{$key}";
331 $document['$unset'][$super_key] = 1;
338 // array getCurrentDocument(bool $update) {{{
340 * Get Current Document
342 * Based on this object properties a new document (Array)
343 * is returned. If we're modifying an document, just the modified
344 * properties are included in this document, which uses $set,
345 * $unset, $pushAll and $pullAll.
348 * @param bool $update
352 final protected function getCurrentDocument($update=false, $current=false)
355 $object = get_document_vars($this);
358 $current = (array)$this->_current
;
362 $this->findReferences($object);
364 $this->triggerEvent('before_validate_'.($update?
'update':'creation'), array(&$object));
365 $this->triggerEvent('before_validate', array(&$object));
367 foreach ($object as $key => $value) {
372 if (is_array($value) && isset($current[$key])) {
374 * If the Field to update is an array, it has a different
375 * behaviour other than $set and $unset. Fist, we need
376 * need to check if it is an array or document, because
377 * they can't be mixed.
380 if (!is_array($current[$key])) {
382 * We're lucky, the field wasn't
383 * an array previously.
385 $this->runFilter($key, $value, $current[$key]);
386 $document['$set'][$key] = $value;
390 if (!$this->getCurrentSubDocument($document, $key, $value, $current[$key])) {
391 throw new Exception("{$key}: Array and documents are not compatible");
393 } else if(!isset($current[$key]) ||
$value !== $current[$key]) {
395 * It is 'linear' field that has changed, or
398 $past_value = isset($current[$key]) ?
$current[$key] : null;
399 $this->runFilter($key, $value, $past_value);
400 $document['$set'][$key] = $value;
404 * It is a document insertation, so we
405 * create the document.
407 $this->runFilter($key, $value, null);
408 $document[$key] = $value;
412 /* Updated behaves in a diff. way */
414 foreach (array_diff(array_keys($this->_current
), array_keys($object)) as $property) {
415 if ($property == '_id') {
418 $document['$unset'][$property] = 1;
422 if (count($document) == 0) {
426 $this->triggerEvent('after_validate_'.($update?
'update':'creation'), array(&$object));
427 $this->triggerEvent('after_validate', array(&$document));
435 // EVENT HANDLERS {{{
437 // addEvent($action, $callback) {{{
442 final static function addEvent($action, $callback)
444 if (!is_callable($callback)) {
445 throw new Exception("Invalid callback");
448 $class = get_called_class();
449 if ($class == __CLASS__
) {
450 $events = & self
::$_super_events;
452 $events = & self
::$_events[$class];
454 if (!isset($events[$action])) {
455 $events[$action] = array();
457 $events[$action][] = $callback;
462 // triggerEvent(string $event, Array $events_params) {{{
463 final function triggerEvent($event, Array $events_params = array())
465 $events = & self
::$_events[get_class($this)][$event];
466 $sevents = & self
::$_super_events[$event];
468 if (!is_array($events_params)) {
472 /* Super-Events handler receives the ActiveMongo class name as first param */
473 $sevents_params = array_merge(array(get_class($this)), $events_params);
475 foreach (array('events', 'sevents') as $event_type) {
476 if (count($
$event_type) > 0) {
477 $params = "{$event_type}_params";
478 foreach ($
$event_type as $fnc) {
479 call_user_func_array($fnc, $
$params);
484 /* Some natives events are allowed to be called
485 * as methods, if they exists
488 case 'before_create':
489 case 'before_update':
490 case 'before_validate':
491 case 'before_delete':
494 case 'after_validate':
496 $fnc = array($this, $event);
497 $params = "events_params";
498 if (is_callable($fnc)) {
499 call_user_func_array($fnc, $
$params);
506 // void runFilter(string $key, mixed &$value, mixed $past_value) {{{
510 * This method check if the current document property has
511 * a filter method, if so, call it.
513 * If the filter returns false, throw an Exception.
517 protected function runFilter($key, &$value, $past_value)
519 $filter = array($this, "{$key}_filter");
520 if (is_callable($filter)) {
521 $filter = call_user_func_array($filter, array(&$value, $past_value));
522 if ($filter===false) {
523 throw new ActiveMongo_FilterException("{$key} filter failed");
525 $this->$key = $value;
532 // void setCursor(MongoCursor $obj) {{{
536 * This method receive a MongoCursor and make
539 * @param MongoCursor $obj
543 final protected function setCursor(MongoCursor
$obj)
545 $this->_cursor
= $obj;
546 $this->setResult($obj->getNext());
550 // void setResult(Array $obj) {{{
554 * This method takes an document and copy it
555 * as properties in this object.
561 final protected function setResult($obj)
563 /* Unsetting previous results, if any */
564 foreach (array_keys(get_document_vars($this, false)) as $key) {
569 /* Add our current resultset as our object's property */
570 foreach ((array)$obj as $key => $value) {
571 if ($key[0] == '$') {
574 $this->$key = $value;
577 /* Save our record */
578 $this->_current
= $obj;
582 // this find([$_id]) {{{
586 * Really simple find, which uses this object properties
589 * @return object this
591 final function find($_id = null)
593 $vars = get_document_vars($this);
594 foreach ($vars as $key => $value) {
598 $parent_class = __CLASS__
;
599 if ($value InstanceOf $parent_class) {
600 $this->getColumnDeference($vars, $key, $value);
601 unset($vars[$key]); /* delete old value */
605 if (is_array($_id)) {
606 $vars['_id'] = array('$in' => $_id);
611 $res = $this->_getCollection()->find($vars);
612 $this->setCursor($res);
617 // void save(bool $async) {{{
621 * This method save the current document in MongoDB. If
622 * we're modifying a document, a update is performed, otherwise
623 * the document is inserted.
625 * On updates, special operations such as $set, $pushAll, $pullAll
626 * and $unset in order to perform efficient updates
632 final function save($async=true)
634 $update = isset($this->_id
) && $this->_id
InstanceOf MongoID
;
635 $conn = $this->_getCollection();
636 $document = $this->getCurrentDocument($update);
637 $object = get_document_vars($this);
638 if (count($document) == 0) {
639 return; /*nothing to do */
643 $this->triggerEvent('before_'.($update ?
'update' : 'create'), array(&$document, $object));
646 $conn->update(array('_id' => $this->_id
), $document, array('safe' => $async));
647 foreach ($document as $key => $value) {
648 if ($key[0] == '$') {
651 $this->_current
[$key] = $value;
654 $conn->insert($document, $async);
655 $this->_id
= $document['_id'];
656 $this->_current
= $document;
659 $this->triggerEvent('after_'.($update ?
'update' : 'create'), array($document, $object));
665 * Delete the current document
669 final function delete()
671 if ($this->_cursor
InstanceOf MongoCursor
) {
672 $document = array('_id' => $this->_id
);
673 $this->triggerEvent('before_delete', array($document));
674 $result = $this->_getCollection()->remove($document);
675 $this->triggerEvent('after_delete', array($document));
676 $this->setResult(array());
679 $criteria = (array) $this->_query
['query'];
682 $this->_getCollection()->remove($criteria);
697 * This method perform multiple updates when a given
698 * criteria matchs (using where).
700 * By default the update is perform safely, but it can be
703 * After the operation is done, the criteria is deleted.
705 * @param array $value Values to set
706 * @param bool $safe Whether or not peform the operation safely
711 function update(Array $value, $safe=true)
713 $this->_assertNotInQuery();
715 $criteria = (array) $this->_query
['query'];
716 $options = array('multiple' => true, 'safe' => $safe);
719 $col = $this->_getCollection();
720 $col->update($criteria, array('$set' => $value), $options);
731 * Delete the current colleciton and all its documents
735 final static function drop()
737 $class = get_called_class();
738 if ($class == __CLASS__
) {
742 return $obj->_getCollection()->drop();
748 * Return the number of documents in the actual request. If
749 * we're not in a request, it will return 0.
753 final function count()
755 if ($this->valid()) {
756 return $this->_cursor
->count();
764 * This method should contain all the indexes, and shard keys
765 * needed by the current collection. This try to make
766 * installation on development environments easier.
773 // bool addIndex(array $columns, array $options) {{{
777 * Create an Index in the current collection.
779 * @param array $columns L ist of columns
780 * @param array $options Options
784 final function addIndex($columns, $options=array())
786 $default_options = array(
790 foreach ($default_options as $option => $value) {
791 if (!isset($options[$option])) {
792 $options[$option] = $value;
796 $collection = $this->_getCollection();
798 return $collection->ensureIndex($columns, $options);
802 // string __toString() {{{
806 * If this object is treated as a string,
807 * it would return its ID.
811 final function __toString()
813 return (string)$this->getID();
817 // array sendCmd(array $cmd) {{{
819 * This method sends a command to the current
822 * @param array $cmd Current command
826 final protected function sendCmd($cmd)
828 return $this->_getConnection()->command($cmd);
836 * Reset our Object, delete the current cursor if any, and reset
841 final function reset()
843 $this->_properties
= null;
844 $this->_cursor
= null;
845 $this->_query
= null;
849 $this->setResult(array());
857 * Return if we're on an iteration and if it is still valid
861 final function valid()
863 if (!$this->_cursor
InstanceOf MongoCursor
) {
866 return $this->_cursor
InstanceOf MongoCursor
&& $this->_cursor
->valid();
872 * Move to the next document
876 final function next()
878 if ($this->_cloned
) {
879 throw new MongoException("Cloned objects can't iterate");
881 return $this->_cursor
->next();
885 // this current() {{{
887 * Return the current object, and load the current document
888 * as this object property
892 final function current()
894 $this->setResult($this->_cursor
->current());
901 * Go to the first document
903 final function rewind()
905 if (!$this->_cursor
InstanceOf MongoCursor
) {
908 return $this->_cursor
->rewind();
915 final function offsetExists($offset)
917 return isset($this->$offset);
920 final function offsetGet($offset)
922 return $this->$offset;
925 final function offsetSet($offset, $value)
927 $this->$offset = $value;
930 final function offsetUnset($offset)
932 unset($this->$offset);
938 // array getReference() {{{
940 * ActiveMongo extended the Mongo references, adding
941 * the concept of 'dynamic' requests, saving in the database
942 * the current query with its options (sort, limit, etc).
944 * This is useful to associate a document with a given
945 * request. To undestand this better please see the 'reference'
950 final function getReference($dynamic=false)
952 if (!$this->getID() && !$dynamic) {
957 '$ref' => $this->getCollectionName(),
958 '$id' => $this->getID(),
959 '$db' => $this->getDatabaseName(),
960 'class' => get_class($this),
963 if ($dynamic && $this->_cursor
InstanceOf MongoCursor
) {
964 $cursor = $this->_cursor
;
965 if (!is_callable(array($cursor, "Info"))) {
966 throw new Exception("Please upgrade your PECL/Mongo module to use this feature");
968 $document['dynamic'] = array();
969 $query = $cursor->Info();
970 foreach ($query as $type => $value) {
971 $document['dynamic'][$type] = $value;
978 // void getDocumentReferences($document, &$refs) {{{
980 * Get Current References
982 * Inspect the current document trying to get any references,
985 * @param array $document Current document
986 * @param array &$refs References found in the document.
987 * @param array $parent_key Parent key
991 final protected function getDocumentReferences($document, &$refs, $parent_key=null)
993 foreach ($document as $key => $value) {
994 if (is_array($value)) {
995 if (MongoDBRef
::isRef($value)) {
998 $refs[] = array('ref' => $value, 'key' => $pkey);
1000 $parent_key[] = $key;
1001 $this->getDocumentReferences($value, $refs, $parent_key);
1008 // object _deferencingCreateObject(string $class) {{{
1010 * Called at deferencig time
1012 * Check if the given string is a class, and it is a sub class
1013 * of ActiveMongo, if it is instance and return the object.
1015 * @param string $class
1019 private function _deferencingCreateObject($class)
1021 if (!is_subclass_of($class, __CLASS__
)) {
1022 throw new MongoException("Fatal Error, imposible to create ActiveMongo object of {$class}");
1028 // void _deferencingRestoreProperty(array &$document, array $keys, mixed $req) {{{
1030 * Called at deferencig time
1032 * This method iterates $document until it could match $keys path, and
1033 * replace its value by $req.
1035 * @param array &$document Document to replace
1036 * @param array $keys Path of property to change
1037 * @param mixed $req Value to replace.
1041 private function _deferencingRestoreProperty(&$document, $keys, $req)
1045 /* find the $req proper spot */
1046 foreach ($keys as $key) {
1047 $obj = & $obj[$key];
1052 /* Delete reference variable */
1057 // object _deferencingQuery($request) {{{
1059 * Called at deferencig time
1061 * This method takes a dynamic reference and request
1064 * @param array $request Dynamic reference
1068 private function _deferencingQuery($request)
1070 $collection = $this->_getCollection();
1071 $cursor = $collection->find($request['query'], $request['fields']);
1072 if ($request['limit'] > 0) {
1073 $cursor->limit($request['limit']);
1075 if ($request['skip'] > 0) {
1076 $cursor->limit($request['limit']);
1079 $this->setCursor($cursor);
1085 // void doDeferencing() {{{
1087 * Perform a deferencing in the current document, if there is
1090 * ActiveMongo will do its best to group references queries as much
1091 * as possible, in order to perform as less request as possible.
1093 * ActiveMongo doesn't rely on MongoDB references, but it can support
1094 * it, but it is prefered to use our referencing.
1098 final function doDeferencing($refs=array())
1100 /* Get current document */
1101 $document = get_document_vars($this);
1103 if (count($refs)==0) {
1104 /* Inspect the whole document */
1105 $this->getDocumentReferences($document, $refs);
1108 $db = $this->_getConnection();
1110 /* Gather information about ActiveMongo Objects
1111 * that we need to create
1114 foreach ($refs as $ref) {
1115 if (!isset($ref['ref']['class'])) {
1117 /* Support MongoDBRef, we do our best to be compatible {{{ */
1118 /* MongoDB 'normal' reference */
1120 $obj = MongoDBRef
::get($db, $ref['ref']);
1122 /* Offset the current document to the right spot */
1123 /* Very inefficient, never use it, instead use ActiveMongo References */
1125 $this->_deferencingRestoreProperty($document, $ref['key'], clone $req);
1127 /* Dirty hack, override our current document
1128 * property with the value itself, in order to
1129 * avoid replace a MongoDB reference by its content
1131 $this->_deferencingRestoreProperty($this->_current
, $ref['key'], clone $req);
1137 if (isset($ref['ref']['dynamic'])) {
1138 /* ActiveMongo Dynamic Reference */
1140 /* Create ActiveMongo object */
1141 $req = $this->_deferencingCreateObject($ref['ref']['class']);
1143 /* Restore saved query */
1144 $req->_deferencingQuery($ref['ref']['dynamic']);
1148 /* Add the result set */
1149 foreach ($req as $result) {
1150 $results[] = clone $result;
1153 /* add information about the current reference */
1154 foreach ($ref['ref'] as $key => $value) {
1155 $results[$key] = $value;
1158 $this->_deferencingRestoreProperty($document, $ref['key'], $results);
1161 /* ActiveMongo Reference FTW! */
1162 $classes[$ref['ref']['class']][] = $ref;
1167 /* {{{ Create needed objects to query MongoDB and replace
1168 * our references by its objects documents.
1170 foreach ($classes as $class => $refs) {
1171 $req = $this->_deferencingCreateObject($class);
1173 /* Load list of IDs */
1175 foreach ($refs as $ref) {
1176 $ids[] = $ref['ref']['$id'];
1179 /* Search to MongoDB once for all IDs found */
1182 if ($req->count() != count($refs)) {
1183 $total = $req->count();
1184 $expected = count($refs);
1185 throw new MongoException("Dereferencing error, MongoDB replied {$total} objects, we expected {$expected}");
1188 /* Replace our references by its objects */
1189 foreach ($refs as $ref) {
1190 $id = $ref['ref']['$id'];
1191 $place = $ref['key'];
1193 while ($req->getID() != $id && $req->next());
1195 assert($req->getID() == $id);
1197 $this->_deferencingRestoreProperty($document, $place, clone $req);
1202 /* Release request, remember we
1209 /* Replace the current document by the new deferenced objects */
1210 foreach ($document as $key => $value) {
1211 $this->$key = $value;
1216 // void getColumnDeference(&$document, $propety, ActiveMongo Obj) {{{
1218 * Prepare a "selector" document to search treaing the property
1219 * as a reference to the given ActiveMongo object.
1222 final function getColumnDeference(&$document, $property, ActiveMongo
$obj)
1224 $document["{$property}.\$id"] = $obj->getID();
1228 // void findReferences(&$document) {{{
1230 * Check if in the current document to insert or update
1231 * exists any references to other ActiveMongo Objects.
1235 final function findReferences(&$document)
1237 if (!is_array($document)) {
1240 foreach($document as &$value) {
1241 $parent_class = __CLASS__
;
1242 if (is_array($value)) {
1243 if (MongoDBRef
::isRef($value)) {
1244 /* If the property we're inspecting is a reference,
1245 * we need to remove the values, restoring the valid
1249 '$ref'=>1, '$id'=>1, '$db'=>1, 'class'=>1, 'dynamic'=>1
1251 foreach (array_keys($value) as $key) {
1252 if (!isset($arr[$key])) {
1253 unset($value[$key]);
1257 $this->findReferences($value);
1259 } else if ($value InstanceOf $parent_class) {
1260 $value = $value->getReference();
1263 /* trick: delete last var. reference */
1268 // void __clone() {{{
1270 * Cloned objects are rarely used, but ActiveMongo
1271 * uses it to create different objects per everyrecord,
1272 * which is used at deferencing. Therefore cloned object
1273 * do not contains the recordset, just the actual document,
1274 * so iterations are not allowed.
1277 final function __clone()
1279 unset($this->_cursor
);
1280 $this->_cloned
= true;
1286 // GET DOCUMENT ID {{{
1290 * Return the current document ID. If there is
1291 * no document it would return false.
1293 * @return object|false
1295 final public function getID()
1297 if ($this->_id
instanceof MongoID
) {
1306 * Return the current key
1310 final function key()
1312 return $this->getID();
1318 // Fancy (and silly) query abstraction {{{
1320 // _assertNotInQuery() {{{
1322 * Check if we can modify the query or not. We cannot modify
1323 * the query if we already asked to MongoDB, in this case the
1324 * object must be reset.
1328 final private function _assertNotInQuery()
1330 if ($this->_cursor
InstanceOf MongoCursor
) {
1331 throw new ActiveMongo_Exception("You cannot modify the query, please reset the object");
1338 * Build the current request and send it to MongoDB.
1342 final function doQuery()
1344 $this->_assertNotInQuery();
1346 $col = $this->_getCollection();
1347 if (count($this->_properties
) > 0) {
1348 $cursor = $col->find((array)$this->_query
['query'], $this->_properties
);
1350 $cursor = $col->find((array)$this->_query
['query']);
1352 if (is_array($this->_sort
)) {
1353 $cursor->sort($this->_sort
);
1355 if ($this->_limit
> 0) {
1356 $cursor->limit($this->_limit
);
1358 if ($this->_skip
> 0) {
1359 $cursor->skip($this->_skip
);
1362 /* Our cursor must be sent to ActiveMongo */
1363 $this->setCursor($cursor);
1369 // properties($props) {{{
1371 * Select 'properties' or 'columns' to be included in the document,
1372 * by default all properties are included.
1374 * @param array $props
1378 final function properties($props)
1380 $this->_assertNotInQuery();
1382 if (!is_array($props) && !is_string($props)) {
1386 if (is_string($props)) {
1387 $props = explode(",", $props);
1390 foreach ($props as $id => $name) {
1391 $props[trim($name)] = 1;
1395 $this->_properties
= $props;
1400 final function columns($properties)
1402 return $this->properties($properties);
1406 // where($property, $value) {{{
1408 * Where abstraction.
1411 final function where($property_str, $value=null)
1413 $this->_assertNotInQuery();
1415 if (is_array($property_str)) {
1416 if ($value != null) {
1417 throw new ActiveMongo_Expception("Invalid parameters");
1419 foreach ($property_str as $property => $value) {
1420 if (is_numeric($property)) {
1424 $this->where($property, $value);
1429 $column = explode(" ", trim($property_str));
1430 if (count($column) != 1 && count($column) != 2) {
1431 throw new ActiveMongo_Exception("Failed while parsing '{$property_str}'");
1432 } else if (count($column) == 2) {
1435 switch (strtolower($column[1])) {
1459 if (is_array($value)) {
1461 $exp_scalar = false;
1470 if (is_array($value)) {
1472 $exp_scalar = false;
1493 $value = new MongoRegex($value);
1500 $exp_scalar = false;
1506 $exp_scalar = false;
1511 /* geo operations */
1515 $exp_scalar = false;
1519 throw new ActiveMongo_Exception("Failed to parse '{$column[1]}'");
1522 if ($exp_scalar && is_array($value)) {
1523 throw new ActiveMongo_Exception("Cannot use comparing operations with Array");
1524 } else if (!$exp_scalar && !is_array($value)) {
1525 throw new ActiveMongo_Exception("The operation {$column[1]} expected an Array");
1529 $value = array($op => $value);
1531 } else if (is_array($value)) {
1532 $value = array('$in' => $value);
1535 $spot = & $this->_query
['query'][$column[0]];
1536 if (is_array($value)) {
1537 $spot[key($value)] = current($value);
1539 /* simulate AND among same properties if
1540 * multiple values is passed for same property
1543 if (is_array($spot)) {
1544 $spot['$all'][] = $value;
1546 $spot = array('$all' => array($spot, $value));
1557 // sort($sort_str) {{{
1559 * Abstract the documents sorting.
1561 * @param string $sort_str List of properties to use as sorting
1565 final function sort($sort_str)
1567 $this->_assertNotInQuery();
1569 $this->_sort
= array();
1570 foreach ((array)explode(",", $sort_str) as $sort_part_str) {
1571 $sort_part = explode(" ", trim($sort_part_str), 2);
1572 switch(count($sort_part)) {
1574 $sort_part[1] = 'ASC';
1579 throw new ActiveMongo_Exception("Don't know how to parse {$sort_part_str}");
1582 switch (strtoupper($sort_part[1])) {
1590 throw new ActiveMongo_Exception("Invalid sorting direction `{$sort_part[1]}`");
1592 $this->_sort
[ $sort_part[0] ] = $sort_part[1];
1599 // limit($limit, $skip) {{{
1601 * Abstract the limitation and pagination of documents.
1603 * @param int $limit Number of max. documents to retrieve
1604 * @param int $skip Number of documents to skip
1608 final function limit($limit=0, $skip=0)
1610 $this->_assertNotInQuery();
1612 if ($limit < 0 ||
$skip < 0) {
1615 $this->_limit
= $limit;
1616 $this->_skip
= $skip;
1626 require_once dirname(__FILE__
)."/Validators.php";
1627 require_once dirname(__FILE__
)."/Exceptions.php";
1634 * vim600: sw=4 ts=4 fdm=marker
1635 * vim<600: sw=4 ts=4