This repository has been archived by the owner on Nov 21, 2019. It is now read-only.
forked from tyohan/MongoRecord
-
Notifications
You must be signed in to change notification settings - Fork 58
/
EMongoDocument.php
1342 lines (1219 loc) · 40.3 KB
/
EMongoDocument.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* EMongoDocument.php
*
* PHP version 5.2+
*
* @author Dariusz Górecki <[email protected]>
* @author Invenzzia Group, open-source division of CleverIT company http://www.invenzzia.org
* @copyright 2011 CleverIT http://www.cleverit.com.pl
* @license http://www.yiiframework.com/license/ BSD license
* @version 1.3
* @category ext
* @package ext.YiiMongoDbSuite
* @since v1.0
*/
/**
* EMongoDocument
*
* @property-read MongoDB $db
* @since v1.0
*/
abstract class EMongoDocument extends EMongoEmbeddedDocument
{
private $_new = false; // whether this instance is new or not
private $_criteria = null; // query criteria (used by finder only)
/**
* Static array that holds mongo collection object instances,
* protected access since v1.3
*
* @var array $_collections static array of loaded collection objects
* @since v1.3
*/
protected static $_collections = array(); // MongoCollection object
private static $_models = array();
private static $_indexes = array(); // Hold collection indexes array
private $_fsyncFlag = null; // Object level FSync flag
private $_safeFlag = null; // Object level Safe flag
protected $useCursor = null; // Whatever to return cursor instead on raw array
/**
* @var boolean $ensureIndexes whatever to check and create non existing indexes of collection
* @since v1.1
*/
protected $ensureIndexes = true; // Whatever to ensure indexes
/**
* EMongoDB component static instance
* @var EMongoDB $_emongoDb;
* @since v1.0
*/
protected static $_emongoDb;
/**
* MongoDB special field, every document has to have this
*
* @var mixed $_id
* @since v1.0
*/
public $_id;
/**
* Add scopes functionality
* @see CComponent::__call()
* @since v1.0
*/
public function __call($name, $parameters)
{
$scopes=$this->scopes();
if(isset($scopes[$name]))
{
$this->getDbCriteria()->mergeWith($scopes[$name]);
return $this;
}
return parent::__call($name,$parameters);
}
/**
* Constructor {@see setScenario()}
*
* @param string $scenario
* @since v1.0
*/
public function __construct($scenario='insert')
{
if($scenario==null) // internally used by populateRecord() and model()
return;
$this->setScenario($scenario);
$this->setIsNewRecord(true);
$this->init();
$this->attachBehaviors($this->behaviors());
$this->afterConstruct();
$this->initEmbeddedDocuments();
}
/**
* Return the primary key field for this collection, defaults to '_id'
* @return string|array field name, or array of fields for composite primary key
* @since v1.2.2
*/
public function primaryKey()
{
return '_id';
}
/**
* @since v1.2.2
*/
public function getPrimaryKey()
{
$pk = $this->primaryKey();
if(is_string($pk))
return $this->{$pk};
else
{
$return = array();
foreach($pk as $pkFiled)
$return[] = $this->{$pkFiled};
return $return;
}
}
/**
* Get EMongoDB component instance
* By default it is mongodb application component
*
* @return EMongoDB
* @since v1.0
*/
public function getMongoDBComponent()
{
if(self::$_emongoDb===null)
self::$_emongoDb = Yii::app()->getComponent('mongodb');
return self::$_emongoDb;
}
/**
* Set EMongoDB component instance
* @param EMongoDB $component
* @since v1.0
*/
public function setMongoDBComponent(EMongoDB $component)
{
self::$_emongoDb = $component;
}
/**
* Get raw MongoDB instance
* @return MongoDB
* @since v1.0
*/
public function getDb()
{
return $this->getMongoDBComponent()->getDbInstance();
}
/**
* This method must return collection name for use with this model
* this must be implemented in child classes
*
* this is read-only defined only at class define
* if you whant to set different colection during run-time
* use {@see setCollection()}
*
* @return string collection name
* @since v1.0
*/
abstract public function getCollectionName();
/**
* Returns current MongoCollection object
* By default this method use {@see getCollectionName()}
* @return MongoCollection
* @since v1.0
*/
public function getCollection()
{
if(!isset(self::$_collections[$this->getCollectionName()]))
self::$_collections[$this->getCollectionName()] = $this->getDb()->selectCollection($this->getCollectionName());
return self::$_collections[$this->getCollectionName()];
}
/**
* Set current MongoCollection object
* @param MongoCollection $collection
* @since v1.0
*/
public function setCollection(MongoCollection $collection)
{
self::$_collections[$this->getCollectionName()] = $collection;
}
/**
* Returns if the current record is new.
* @return boolean whether the record is new and should be inserted when calling {@link save}.
* This property is automatically set in constructor and {@link populateRecord}.
* Defaults to false, but it will be set to true if the instance is created using
* the new operator.
* @since v1.0
*/
public function getIsNewRecord()
{
return $this->_new;
}
/**
* Sets if the record is new.
* @param boolean $value whether the record is new and should be inserted when calling {@link save}.
* @see getIsNewRecord
* @since v1.0
*/
public function setIsNewRecord($value)
{
$this->_new=$value;
}
/**
* Returns the mongo criteria associated with this model.
* @param boolean $createIfNull whether to create a criteria instance if it does not exist. Defaults to true.
* @return EMongoCriteria the query criteria that is associated with this model.
* This criteria is mainly used by {@link scopes named scope} feature to accumulate
* different criteria specifications.
* @since v1.0
*/
public function getDbCriteria($createIfNull=true)
{
if($this->_criteria===null)
if(($c = $this->defaultScope()) !== array() || $createIfNull)
$this->_criteria = new EMongoCriteria($c);
return $this->_criteria;
}
/**
* Set girrent object, this will override proevious criteria
*
* @param EMongoCriteria $criteria
* @since v1.0
*/
public function setDbCriteria($criteria)
{
if(is_array($criteria))
$this->_criteria = new EMongoCriteria($criteria);
else if($criteria instanceof EMongoCriteria)
$this->_criteria = $criteria;
else
$this->_criteria = new EMongoCriteria();
}
/**
* Get FSync flag
*
* It will return the nearest not null value in order:
* - Object level
* - Model level
* - Glopal level (always set)
* @return boolean
*/
public function getFsyncFlag()
{
if($this->_fsyncFlag !== null)
return $this->_fsyncFlag; // We have flag set, return it
if((isset(self::$_models[get_class($this)]) === true) && (self::$_models[get_class($this)]->_fsyncFlag !== null))
return self::$_models[get_class($this)]->_fsyncFlag; // Model have flag set, return it
return $this->getMongoDBComponent()->fsyncFlag;
}
/**
* Set object level FSync flag
* @param boolean $flag true|false value for FSync flag
*/
public function setFsyncFlag($flag)
{
$this->_fsyncFlag = ($flag == true);
if($this->_fsyncFlag)
$this->setSafeFlag(true); // Setting FSync flag to true will implicit set safe to true
}
/**
* Get Safe flag
*
* It will return the nearest not null value in order:
* - Object level
* - Model level
* - Glopal level (always set)
* @return boolean
*/
public function getSafeFlag()
{
if($this->_safeFlag !== null)
return $this->_safeFlag; // We have flag set, return it
if((isset(self::$_models[get_class($this)]) === true) && (self::$_models[get_class($this)]->_safeFlag !== null))
return self::$_models[get_class($this)]->_safeFlag; // Model have flag set, return it
return $this->getMongoDBComponent()->safeFlag;
}
/**
* Set object level Safe flag
* @param boolean $flag true|false value for Safe flag
*/
public function setSafeFlag($flag)
{
$this->_safeFlag = ($flag == true);
}
/**
* Get value of use cursor flag
*
* It will return the nearest not null value in order:
* - Object level
* - Model level
* - Glopal level (always set)
* @return boolean
*/
public function getUseCursor()
{
if($this->useCursor !== null)
return $this->useCursor; // We have flag set, return it
if((isset(self::$_models[get_class($this)]) === true) && (self::$_models[get_class($this)]->useCursor !== null))
return self::$_models[get_class($this)]->useCursor; // Model have flag set, return it
return $this->getMongoDBComponent()->useCursor;
}
/**
* Set object level value of use cursor flag
* @param boolean $useCursor true|false value for use cursor flag
*/
public function setUseCursor($useCursor)
{
$this->useCursor = ($useCursor == true);
}
/**
* Sets the attribute values in a massive way.
* @param array $values attribute values (name=>value) to be set.
* @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
* A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
* @see getSafeAttributeNames
* @see attributeNames
* @since v1.3.1
*/
public function setAttributes($values, $safeOnly=true)
{
if(!is_array($values))
return;
if($this->hasEmbeddedDocuments())
{
$attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
foreach($this->embeddedDocuments() as $fieldName => $className)
if(isset($values[$fieldName]) && isset($attributes[$fieldName]))
{
$this->$fieldName->setAttributes($values[$fieldName], $safeOnly);
unset($values[$fieldName]);
}
}
parent::setAttributes($values, $safeOnly);
}
/**
* This function check indexes and applies them to the collection if needed
* see CModel::init()
*
* @see EMongoEmbeddedDocument::init()
* @since v1.1
*/
public function init()
{
parent::init();
if($this->ensureIndexes && !isset(self::$_indexes[$this->getCollectionName()]))
{
$indexInfo = $this->getCollection()->getIndexInfo();
array_shift($indexInfo); // strip out default _id index
$indexes = array();
foreach($indexInfo as $index)
{
$indexes[$index['name']] = array(
'key'=>$index['key'],
'unique'=>isset($index['unique']) ? $index['unique'] : false,
);
}
self::$_indexes[$this->getCollectionName()] = $indexes;
$this->ensureIndexes();
}
}
/**
* This function may return array of indexes for this collection
* array sytntax is:
* return array(
* 'index_name'=>array('key'=>array('fieldName1'=>EMongoCriteria::SORT_ASC, 'fieldName2'=>EMongoCriteria::SORT_DESC),
* 'index2_name'=>array('key'=>array('fieldName3'=>EMongoCriteria::SORT_ASC, 'unique'=>true),
* );
* @return array list of indexes for this collection
* @since v1.1
*/
public function indexes()
{
return array();
}
/**
* @since v1.1
*/
private function ensureIndexes()
{
$indexNames = array_keys(self::$_indexes[$this->getCollectionName()]);
foreach($this->indexes() as $name=>$index)
{
if(!in_array($name, $indexNames))
{
if(version_compare(Mongo::VERSION, '1.0.2','>=') === true)
{
$this->getCollection()->ensureIndex(
$index['key'],
array('unique'=>isset($index['unique']) ? $index['unique'] : false, 'name'=>$name)
);
} else {
$this->getCollection()->ensureIndex(
$index['key'],
isset($index['unique']) ? $index['unique'] : false
);
}
self::$_indexes[$this->getCollectionName()][$name] = $index;
}
}
}
/**
* Returns the declaration of named scopes.
* A named scope represents a query criteria that can be chained together with
* other named scopes and applied to a query. This method should be overridden
* by child classes to declare named scopes for the particular document classes.
* For example, the following code declares two named scopes: 'recently' and
* 'published'.
* <pre>
* return array(
* 'published'=>array(
* 'conditions'=>array(
* 'status'=>array('==', 1),
* ),
* ),
* 'recently'=>array(
* 'sort'=>array('create_time'=>EMongoCriteria::SORT_DESC),
* 'limit'=>5,
* ),
* );
* </pre>
* If the above scopes are declared in a 'Post' model, we can perform the following
* queries:
* <pre>
* $posts=Post::model()->published()->findAll();
* $posts=Post::model()->published()->recently()->findAll();
* $posts=Post::model()->published()->published()->recently()->find();
* </pre>
*
* @return array the scope definition. The array keys are scope names; the array
* values are the corresponding scope definitions. Each scope definition is represented
* as an array whose keys must be properties of {@link EMongoCriteria}.
* @since v1.0
*/
public function scopes()
{
return array();
}
/**
* Returns the default named scope that should be implicitly applied to all queries for this model.
* Note, default scope only applies to SELECT queries. It is ignored for INSERT, UPDATE and DELETE queries.
* The default implementation simply returns an empty array. You may override this method
* if the model needs to be queried with some default criteria (e.g. only active records should be returned).
* @return array the mongo criteria. This will be used as the parameter to the constructor
* of {@link EMongoCriteria}.
* @since v1.2.2
*/
public function defaultScope()
{
return array();
}
/**
* Resets all scopes and criterias applied including default scope.
*
* @return EMongoDocument
* @since v1.0
*/
public function resetScope()
{
$this->_criteria = new EMongoCriteria();
return $this;
}
/**
* Applies the query scopes to the given criteria.
* This method merges {@link dbCriteria} with the given criteria parameter.
* It then resets {@link dbCriteria} to be null.
* @param EMongoCriteria|array $criteria the query criteria. This parameter may be modified by merging {@link dbCriteria}.
* @since v1.2.2
*/
public function applyScopes(&$criteria)
{
if($criteria === null)
{
$criteria = new EMongoCriteria();
}
else if(is_array($criteria))
{
$criteria = new EMongoCriteria($criteria);
}
else if(!($criteria instanceof EMongoCriteria))
throw new EMongoException('Cannot apply scopes to criteria');
if(($c=$this->getDbCriteria(false))!==null)
{
$c->mergeWith($criteria);
$criteria=$c;
$this->_criteria=null;
}
}
/**
* Saves the current record.
*
* The record is inserted as a row into the database table if its {@link isNewRecord}
* property is true (usually the case when the record is created using the 'new'
* operator). Otherwise, it will be used to update the corresponding row in the table
* (usually the case if the record is obtained using one of those 'find' methods.)
*
* Validation will be performed before saving the record. If the validation fails,
* the record will not be saved. You can call {@link getErrors()} to retrieve the
* validation errors.
*
* If the record is saved via insertion, its {@link isNewRecord} property will be
* set false, and its {@link scenario} property will be set to be 'update'.
* And if its primary key is auto-incremental and is not set before insertion,
* the primary key will be populated with the automatically generated key value.
*
* @param boolean $runValidation whether to perform validation before saving the record.
* If the validation fails, the record will not be saved to database.
* @param array $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the saving succeeds
* @since v1.0
*/
public function save($runValidation=true,$attributes=null)
{
if(!$runValidation || $this->validate($attributes))
return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
else
return false;
}
/**
* Inserts a row into the table based on this active record attributes.
* If the table's primary key is auto-incremental and is null before insertion,
* it will be populated with the actual value after insertion.
* Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
* After the record is inserted to DB successfully, its {@link isNewRecord} property will be set false,
* and its {@link scenario} property will be set to be 'update'.
* @param array $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @return boolean whether the attributes are valid and the record is inserted successfully.
* @throws CException if the record is not new
* @throws EMongoException on fail of insert or insert of empty document
* @throws MongoCursorException on fail of insert, when safe flag is set to true
* @throws MongoCursorTimeoutException on timeout of db operation , when safe flag is set to true
* @since v1.0
*/
public function insert(array $attributes=null)
{
if(!$this->getIsNewRecord())
throw new CDbException(Yii::t('yii','The EMongoDocument cannot be inserted to database because it is not new.'));
if($this->beforeSave())
{
Yii::trace(get_class($this).'.insert()','ext.MongoDb.EMongoDocument');
$rawData = $this->toArray();
// free the '_id' container if empty, mongo will not populate it if exists
if(empty($rawData['_id']))
unset($rawData['_id']);
// filter attributes if set in param
if($attributes!==null)
{
foreach($rawData as $key=>$value)
{
if(!in_array($key, $attributes))
unset($rawData[$key]);
}
}
if(version_compare(Mongo::VERSION, '1.0.5','>=') === true)
$result = $this->getCollection()->insert($rawData, array(
'fsync' => $this->getFsyncFlag(),
'safe' => $this->getSafeFlag()
));
else
$result = $this->getCollection()->insert($rawData, CPropertyValue::ensureBoolean($this->getSafeFlag()));
if($result !== false) // strict comparison needed
{
$this->_id = $rawData['_id'];
$this->setIsNewRecord(false);
$this->setScenario('update');
$this->afterSave();
return true;
}
throw new EMongoException(Yii::t('yii', 'Can\t save document to disk, or try to save empty document!'));
}
return false;
}
/**
* Updates the row represented by this active record.
* All loaded attributes will be saved to the database.
* Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
* @param array $attributes list of attributes that need to be saved. Defaults to null,
* meaning all attributes that are loaded from DB will be saved.
* @param boolean modify if set true only selected attributes will be replaced, and not
* the whole document
* @return boolean whether the update is successful
* @throws CException if the record is new
* @throws EMongoException on fail of update
* @throws MongoCursorException on fail of update, when safe flag is set to true
* @throws MongoCursorTimeoutException on timeout of db operation , when safe flag is set to true
* @since v1.0
*/
public function update(array $attributes=null, $modify = false)
{
if($this->getIsNewRecord())
throw new CDbException(Yii::t('yii','The EMongoDocument cannot be updated because it is new.'));
if($this->beforeSave())
{
Yii::trace(get_class($this).'.update()','ext.MongoDb.EMongoDocument');
$rawData = $this->toArray();
// filter attributes if set in param
if($attributes!==null)
{
if (!in_array('_id', $attributes) && !$modify) $attributes[] = '_id'; // This is very easy to forget
foreach($rawData as $key=>$value)
{
if(!in_array($key, $attributes))
unset($rawData[$key]);
}
}
if($modify)
{
if(isset($rawData['_id']) === true)
unset($rawData['_id']);
$result = $this->getCollection()->update(
array('_id' => $this->_id),
array('$set' => $rawData),
array(
'fsync'=>$this->getFsyncFlag(),
'safe'=>$this->getSafeFlag(),
'multiple'=>false
)
);
} else {
if(version_compare(Mongo::VERSION, '1.0.5','>=') === true)
$result = $this->getCollection()->save($rawData, array(
'fsync'=>$this->getFsyncFlag(),
'safe'=>$this->getSafeFlag()
));
else
$result = $this->getCollection()->save($rawData);
}
if($result !== false) // strict comparison needed
{
$this->afterSave();
return true;
}
throw new CException(Yii::t('yii', 'Can\t save document to disk, or try to save empty document!'));
}
}
/**
* Atomic, in-place update method.
*
* @since v1.3.6
* @param EMongoModifier $modifier updating rules to apply
* @param EMongoCriteria $criteria condition to limit updating rules
* @return bool
*/
public function updateAll($modifier, $criteria=null) {
Yii::trace(get_class($this).'.updateAll()','ext.MongoDb.EMongoDocument');
if($modifier->canApply === true)
{
$this->applyScopes($criteria);
if(version_compare(Mongo::VERSION, '1.0.5','>=') === true)
$result = $this->getCollection()->update($criteria->getConditions(), $modifier->getModifiers(), array(
'fsync'=>$this->getFsyncFlag(),
'safe'=>$this->getSafeFlag(),
'upsert'=>false,
'multiple'=>true
));
else
$result = $this->getCollection()->update($criteria->getConditions(), $modifier->getModifiers(), array(
'upsert'=>false,
'multiple'=>true
));
return $result;
} else {
return false;
}
}
/**
* Deletes the row corresponding to this EMongoDocument.
* @return boolean whether the deletion is successful.
* @throws CException if the record is new
* @since v1.0
*/
public function delete()
{
if(!$this->getIsNewRecord())
{
Yii::trace(get_class($this).'.delete()','ext.MongoDb.EMongoDocument');
if($this->beforeDelete())
{
$result = $this->deleteByPk($this->getPrimaryKey());
if($result !== false)
{
$this->afterDelete();
$this->setIsNewRecord(true);
return true;
}
else
return false;
}
else
return false;
}
else
throw new CDbException(Yii::t('yii','The EMongoDocument cannot be deleted because it is new.'));
}
/**
* Deletes document with the specified primary key.
* See {@link find()} for detailed explanation about $condition and $params.
* @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
* @param array|EMongoCriteria $condition query criteria.
* @since v1.0
*/
public function deleteByPk($pk, $criteria=null)
{
Yii::trace(get_class($this).'.deleteByPk()','ext.MongoDb.EMongoDocument');
if($this->beforeDelete())
{
$this->applyScopes($criteria);
$criteria->mergeWith($this->createPkCriteria($pk));
if(version_compare(Mongo::VERSION, '1.0.5','>=') === true)
$result = $this->getCollection()->remove($criteria->getConditions(), array(
'justOne'=>true,
'fsync'=>$this->getFsyncFlag(),
'safe'=>$this->getSafeFlag()
));
else
$result = $this->getCollection()->remove($criteria->getConditions(), true);
$this->afterDelete();
return $result;
}
return false;
}
/**
* Repopulates this active record with the latest data.
* @return boolean whether the row still exists in the database. If true, the latest data will be populated to this active record.
* @since v1.0
*/
public function refresh()
{
Yii::trace(get_class($this).'.refresh()','ext.MongoDb.EMongoDocument');
if(!$this->getIsNewRecord() && $this->getCollection()->count(array('_id'=>$this->_id))==1)
{
$this->setAttributes($this->getCollection()->find(array('_id'=>$this->_id)), false);
return true;
}
else
return false;
}
/**
* Finds a single EMongoDocument with the specified condition.
* @param array|EMongoCriteria $condition query criteria.
*
* If an array, it is treated as the initial values for constructing a {@link EMongoCriteria} object;
* Otherwise, it should be an instance of {@link EMongoCriteria}.
*
* @return EMongoDocument the record found. Null if no record is found.
* @since v1.0
*/
public function find($criteria=null)
{
Yii::trace(get_class($this).'.find()','ext.MongoDb.EMongoDocument');
if($this->beforeFind())
{
$this->applyScopes($criteria);
$doc = $this->getCollection()->findOne($criteria->getConditions(), $criteria->getSelect());
return $this->populateRecord($doc);
}
return null;
}
/**
* Finds all documents satisfying the specified condition.
* See {@link find()} for detailed explanation about $condition and $params.
* @param array|EMongoCriteria $condition query criteria.
* @return array list of documents satisfying the specified condition. An empty array is returned if none is found.
* @since v1.0
*/
public function findAll($criteria=null)
{
Yii::trace(get_class($this).'.findAll()','ext.MongoDb.EMongoDocument');
if($this->beforeFind())
{
$this->applyScopes($criteria);
$cursor = $this->getCollection()->find($criteria->getConditions());
if($criteria->getSort() !== null)
$cursor->sort($criteria->getSort());
if($criteria->getLimit() !== null)
$cursor->limit($criteria->getLimit());
if($criteria->getOffset() !== null)
$cursor->skip($criteria->getOffset());
if($criteria->getSelect())
$cursor->fields($criteria->getSelect(true));
if($this->getUseCursor())
return new EMongoCursor($cursor, $this->model());
else
return $this->populateRecords($cursor);
}
return array();
}
/**
* Finds document with the specified primary key.
* In MongoDB world every document has '_id' unique field, so with this method that
* field is in use as PK!
* See {@link find()} for detailed explanation about $condition.
* @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
* @param array|EMongoCriteria $condition query criteria.
* @return the document found. An null is returned if none is found.
* @since v1.0
*/
public function findByPk($pk, $criteria=null)
{
Yii::trace(get_class($this).'.findByPk()','ext.MongoDb.EMongoDocument');
$criteria = new EMongoCriteria($criteria);
$criteria->mergeWith($this->createPkCriteria($pk));
return $this->find($criteria);
}
/**
* Finds all documents with the specified primary keys.
* In MongoDB world every document has '_id' unique field, so with this method that
* field is in use as PK by default.
* See {@link find()} for detailed explanation about $condition.
* @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
* @param array|EMongoCriteria $condition query criteria.
* @return the document found. An null is returned if none is found.
* @since v1.0
*/
public function findAllByPk($pk, $criteria=null)
{
Yii::trace(get_class($this).'.findAllByPk()','ext.MongoDb.EMongoDocument');
$criteria = new EMongoCriteria($criteria);
$criteria->mergeWith($this->createPkCriteria($pk, true));
return $this->findAll($criteria);
}
/**
* Finds document with the specified attributes.
*
* See {@link find()} for detailed explanation about $condition.
* @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
* @param array|EMongoCriteria $condition query criteria.
* @return the document found. An null is returned if none is found.
* @since v1.0
*/
public function findByAttributes(array $attributes)
{
$criteria = new EMongoCriteria();
foreach($attributes as $name=>$value)
{
$criteria->$name('==', $value);
}
return $this->find($criteria);
}
/**
* Finds all documents with the specified attributes.
*
* See {@link find()} for detailed explanation about $condition.
* @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
* @param array|EMongoCriteria $condition query criteria.
* @return the document found. An null is returned if none is found.
* @since v1.0
*/
public function findAllByAttributes(array $attributes)
{
$criteria = new EMongoCriteria();
foreach($attributes as $name=>$value)
{
$criteria->$name('==', $value);
}
return $this->findAll($criteria);
}
/**
* Counts all documents satisfying the specified condition.
* See {@link find()} for detailed explanation about $condition and $params.
* @param array|EMongoCriteria $condition query criteria.
* @return integer Count of all documents satisfying the specified condition.
* @since v1.0
*/
public function count($criteria=null)
{
Yii::trace(get_class($this).'.count()','ext.MongoDb.EMongoDocument');
$this->applyScopes($criteria);
return $this->getCollection()->count($criteria->getConditions());
}
/**
* Counts all documents satisfying the specified condition.
* See {@link find()} for detailed explanation about $condition and $params.
* @param array|EMongoCriteria $condition query criteria.
* @return integer Count of all documents satisfying the specified condition.
* @since v1.2.2
*/
public function countByAttributes(array $attributes)
{
Yii::trace(get_class($this).'.countByAttributes()','ext.MongoDb.EMongoDocument');
$criteria = new EMongoCriteria;
foreach($attributes as $name=>$value)
$criteria->$name = $value;
$this->applyScopes($criteria);
return $this->getCollection()->count($criteria->getConditions());
}
/**
* Deletes documents with the specified primary keys.
* See {@link find()} for detailed explanation about $condition and $params.
* @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
* @param array|EMongoCriteria $condition query criteria.
* @since v1.0
*/
public function deleteAll($criteria=null)
{
Yii::trace(get_class($this).'.deleteByPk()','ext.MongoDb.EMongoDocument');
$this->applyScopes($criteria);
if(version_compare(Mongo::VERSION, '1.0.5','>=') === true)
return $this->getCollection()->remove($criteria->getConditions(), array(
'justOne'=>false,
'fsync'=>$this->getFsyncFlag(),
'safe'=>$this->getSafeFlag()
));
else
return $this->getCollection()->remove($criteria->getConditions(), false);
}