forked from Sammaye/MongoYii
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EMongoDocument.php
executable file
·1497 lines (1355 loc) · 43.8 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
*
* The active record itself
*/
class EMongoDocument extends EMongoModel
{
/**
* Holds a set of cached models for the active record to instantiate from
*
* Whenever you call ::model() it will either find the class in this cache array and use it or will
* make a whole new class and cache it into this array
*
* @var array
*/
private static $_models = array();
/**
* Whether or not the document is new
* @var boolean
*/
private $_new = false;
/**
* Holds criteria information for scopes
* @var array|null
*/
private $_criteria;
/**
* Contains a list of fields that were projected, will only be taken into consideration
* should _partial be true
* @var array|string[]
*/
private $_projected_fields = array();
/**
* A bit deceptive, this var actually holds the last response from the server. The reason why it is called this
* is because this is what MongoDB calls it.
* @var array
*/
private $lastError;
/**
* Sets up our model and set the field cache just like in EMongoModel
*
* It will also set the default scope on the model so be aware that if you want the default scope to not be applied you will
* need to run resetScope() straight after making this model
*
* @param string $scenario
*/
public function __construct($scenario = 'insert')
{
$this->getDbConnection()->setDocumentCache($this);
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, in addition to EMongoModels edition, will also call scopes on the model
* @see EMongoModel::__call()
* @param string $name
* @param array $parameters
* @return EMongoDocument|mixed
*/
public function __call($name, $parameters){
if(array_key_exists($name, $this->relations())){
if(empty($parameters)){
return $this->getRelated($name, false);
}
return $this->getRelated($name, false, $parameters[0]);
}
$scopes = $this->scopes();
if(isset($scopes[$name])){
$this->setDbCriteria($this->mergeCriteria($this->getDbCriteria(), $scopes[$name]));
return $this;
}
return parent::__call($name, $parameters);
}
/**
* The scope attached to this model
*
* It is very much like how Yii normally uses scopes except the params are slightly different.
*
* @example
*
* array(
* 'ten_recently_published' => array(
* 'condition' => array('published' => 1),
* 'sort' => array('date_published' => -1),
* 'skip' => 5,
* 'limit' => 10
* )
* )
*
* Not all params need to be defined they are all just there above to give an indea of how to use this
*
* @return array
*/
public function scopes()
{
return array();
}
/**
* Sets the default scope
*
* @example
*
* array(
* 'condition' => array('published' => 1),
* 'sort' => array('date_published' => -1),
* 'skip' => 5,
* 'limit' => 10
* )
*
* @return array - An array which represents a single scope within the scope() function
*/
public function defaultScope()
{
return array();
}
/**
* Resets the scopes applied to the model clearing the _criteria variable
* @param bool $resetDefault
* @return EMongoDocument
*/
public function resetScope($resetDefault = true)
{
$this->_criteria = ($resetDefault ? array() : null);
return $this;
}
/**
* Returns the collection name as a string
*
* @example
*
* return 'users';
*
* @return string
*/
public function collectionName()
{
return get_class($this);
}
/**
* Denotes whether or not this document is versioned
* @return boolean
*/
public function versioned()
{
return false;
}
/**
* Denotes the field tob e used to house the version number
* @return string
*/
public function versionField()
{
return '_v';
}
/**
* Returns MongoId based on $value
*
* @deprecated This function will become deprecated in favour of consistently
* using the getPrimaryKey() function instead. Atm, however, the getPrimaryKey
* function actually chains onto this method. If you see this and are wondering
* about what you should do if you want custom primary keys etc just use the getPrimaryKey
* function as you would the getMongoId function. These two functions should never have been separate
* for they are the same essentially.
*
* As to what version this will become deprecated:- I dunno. It will not be soon since it will be a
* functionality breaker...
*
* @param string|MongoId $value
* @return MongoId
*/
public function getMongoId($value = null)
{
return $value instanceof MongoId ? $value : new MongoId($value);
}
/**
* Returns the value of the primary key
* @param string|MongoId $value
* @return MongoId
*/
public function getPrimaryKey($value = null)
{
if($value === null){
$value = $this->{$this->primaryKey()};
}
return $this->getMongoId($value);
}
/**
* Returns if the current record is new.
* 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.
* @return boolean
*/
public function getIsNewRecord()
{
return $this->_new;
}
/**
* Sets if the record is new.
* Whether the record is new and should be inserted when calling {@link save}.
* @see EMongoDocument::getIsNewRecord()
* @param boolean $value
*/
public function setIsNewRecord($value)
{
$this->_new = (bool)$value;
}
/**
* Gets a list of the projected fields for the model
* @return array|string[]
*/
public function getProjectedFields()
{
return $this->_projected_fields;
}
/**
* Sets the projected fields of the model
* @param array|string[] $fields
*/
public function setProjectedFields(array $fields)
{
$this->_projected_fields = $fields;
}
/**
* Gets the version of this document
* @return string
*/
public function version()
{
return $this->{$this->versionField()};
}
/**
* Forceably increments the version of this document
* @return bool
*/
public function incrementVersion()
{
$resp = $this->updateByPk($this->getPrimaryKey(), array('$inc' => array($this->versionField() => 1)));
if($resp['n'] <= 0){
return false;
}
$this->{$this->versionField()} += 1;
return true;
}
/**
* Forceably sets the version of this document
* @param mixed $n
* @return bool
*/
public function setVersion($n)
{
$resp = $this->updateByPk($this->getPrimaryKey(), array('$set' => array($this->versionField() => $n)));
if($resp['n'] <= 0){
return false;
}
$this->{$this->versionField()} = $n;
return true;
}
/**
* Sets the attribute of the model
* @param string $name
* @param mixed $value
* @return bool
*/
public function setAttribute($name, $value)
{
// At the moment the projection is restricted to only fields returned in result set
// Uncomment this to change that
//if($this->getIsPartial())
// $this->_projected_fields[$name] = 1;
return parent::setAttribute($name, $value);
}
/**
* Returns the static model of the specified AR class.
* The model returned is a static instance of the AR class.
* It is provided for invoking class-level methods (something similar to static class methods.)
*
* EVERY derived AR class must override this method as follows,
* <pre>
* public static function model($className=__CLASS__)
* {
* return parent::model($className);
* }
* </pre>
*
* @param string $className
* @return EMongoDocument
*/
public static function model($className = __CLASS__)
{
if(isset(self::$_models[$className])){
return self::$_models[$className];
}
/** @var EMongoDocument $model */
$model = self::$_models[$className] = new $className(null);
$model->attachBehaviors($model->behaviors());
return $model;
}
/**
* Instantiates a model from an array
* @param array $document
* @return EMongoDocument
*/
protected function instantiate($document)
{
$class = get_class($this);
return new $class(null);
}
/**
* Returns the text label for the specified attribute.
* This method overrides the parent implementation by supporting
* returning the label defined in relational object.
* In particular, if the attribute name is in the form of "post.author.name",
* then this method will derive the label from the "author" relation's "name" attribute.
* @see CModel::generateAttributeLabel()
* @param string $attribute - the attribute name
* @return string - the attribute label
*/
public function getAttributeLabel($attribute)
{
$labels = $this->attributeLabels();
if(isset($labels[$attribute])){
return $labels[$attribute];
}
if(strpos($attribute, '.') === false){
return $this->generateAttributeLabel($attribute);
}
$segs = explode('.', $attribute);
$name = array_pop($segs);
$model = $this;
foreach($segs as $seg){
$relations = $model->relations();
if(!isset($relations[$seg])){
break;
}
$model = EMongoDocument::model($relations[$seg][1]);
}
return $model->getAttributeLabel($name);
}
/**
* Creates an active record with the given attributes.
* This method is internally used by the find methods.
* Null is returned if the input data is false.
*
* @param array $attributes - attribute values (column name=>column value)
* @param boolean $callAfterFind whether to call {@link afterFind} after the record is populated.
* @param bool $partial
* @return EMongoDocument|null - the newly created active record. The class of the object is the same as the model class.
*/
public function populateRecord($attributes, $callAfterFind = true, $partial = false)
{
if($attributes === false || $attributes === null){
return null;
}
$record = $this->instantiate($attributes);
$record->setScenario('update');
$record->setIsNewRecord(false);
$record->init();
$labels = array();
foreach($attributes as $name=>$value){
$labels[$name] = 1;
$record->setAttribute($name, $value);
}
if($partial){
$record->setIsPartial(true);
$record->setProjectedFields($labels);
}
//$record->_pk=$record->primaryKey();
$record->attachBehaviors($record->behaviors());
if($callAfterFind){
$record->afterFind();
}
return $record;
}
/**
* Returns an array of records populated by incoming data
* @param array $data
* @param bool $callAfterFind
* @param string $index
* @return array - Array of the records
*/
public function populateRecords(array $data, $callAfterFind = true, $index = null)
{
$records = array();
foreach($data as $attributes){
if(($record = $this->populateRecord($attributes, $callAfterFind)) !== null){
if($index === null){
$records[] = $record;
}else{
$records[$record->$index] = $record;
}
}
}
return $records;
}
/**********/
/* Events */
/**********/
/**
* @param CEvent $event
*/
public function onBeforeSave($event)
{
$this->raiseEvent('onBeforeSave', $event);
}
/**
* @param CEvent $event
*/
public function onAfterSave($event)
{
$this->raiseEvent('onAfterSave', $event);
}
/**
* @param CEvent $event
*/
public function onBeforeDelete($event)
{
$this->raiseEvent('onBeforeDelete', $event);
}
/**
* @param CEvent $event
*/
public function onAfterDelete($event)
{
$this->raiseEvent('onAfterDelete', $event);
}
/**
* @param CEvent $event
*/
public function onBeforeFind($event)
{
$this->raiseEvent('onBeforeFind', $event);
}
/**
* @param CEvent $event
*/
public function onAfterFind($event)
{
$this->raiseEvent('onAfterFind', $event);
}
/**
* @return bool
*/
protected function beforeSave()
{
if($this->hasEventHandler('onBeforeSave')){
$event = new CModelEvent($this);
$this->onBeforeSave($event);
return $event->isValid;
}
return true;
}
protected function afterSave()
{
if($this->hasEventHandler('onAfterSave')){
$this->onAfterSave(new CEvent($this));
}
}
/**
* @return bool
*/
protected function beforeDelete()
{
if($this->hasEventHandler('onBeforeDelete')){
$event = new CModelEvent($this);
$this->onBeforeDelete($event);
return $event->isValid;
}
return true;
}
protected function afterDelete()
{
if($this->hasEventHandler('onAfterDelete')){
$this->onAfterDelete(new CEvent($this));
}
}
protected function beforeFind()
{
if($this->hasEventHandler('onBeforeFind')){
$event = new CModelEvent($this);
$this->onBeforeFind($event);
}
}
protected function afterFind()
{
if($this->hasEventHandler('onAfterFind')){
$this->onAfterFind(new CEvent($this));
}
}
/**
* Saves this record
*
* If an attributes specification is sent in it will only validate and save those attributes
*
* @param boolean $runValidation
* @param array $attributes
* @return bool
*/
public function save($runValidation = true, $attributes = null){
if(!$runValidation || $this->validate($attributes)){
return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
}
return false;
}
/**
* Saves only a specific subset of attributes as defined by the param
* @param array $attributes
* @return bool
* @throws EMongoException
*/
public function saveAttributes($attributes)
{
if($this->getIsNewRecord()){
throw new EMongoException(Yii::t('yii', 'The active record cannot be updated because it is new.'));
}
$this->trace(__FUNCTION__);
$values = array();
foreach($attributes as $name => $value){
if(is_integer($name)){
$v = $this->$value;
if(is_array($this->$value)){
$v = $this->filterRawDocument($this->$value);
}
$values[$value] = $v;
}else{
$values[$name] = $this->$name = $value;
}
}
if(!isset($this->{$this->primaryKey()}) || $this->getPrimaryKey() === null){
throw new EMongoException(Yii::t('yii', 'The active record cannot be updated because its _id is not set!'));
}
return $this->lastError = $this->updateByPk($this->getPrimaryKey(), array('$set' => $values));
}
/**
* Inserts this record
* @param array $attributes
* @return bool
* @throws EMongoException
*/
public function insert($attributes = null)
{
if(!$this->getIsNewRecord()){
throw new EMongoException(Yii::t('yii', 'The active record cannot be inserted to database because it is not new.'));
}
if(!$this->beforeSave()){
return false;
}
$this->trace(__FUNCTION__);
if($attributes !== null){
$document = $this->filterRawDocument($this->getAttributes($attributes));
}else{
$document = $this->getRawDocument();
}
if($this->versioned()){
$document[$this->versionField()] = $this->{$this->versionField()} = 1;
}
if(!isset($this->{$this->primaryKey()})){
$document['_id'] = $this->{$this->primaryKey()} = $this->getPrimaryKey();
}
if(YII_DEBUG){
// we're actually physically testing for Yii debug mode here to stop us from
// having to do the serialisation on the update doc normally.
Yii::trace('Executing insert: {$document:' . json_encode($document) . '}', 'extensions.MongoYii.EMongoDocument');
}
if($this->getDbConnection()->enableProfiling){
Yii::beginProfile(
'extensions.MongoYii.EMongoDocument.query.' . $this->collectionName() . '.insert(' . '{$document:' . json_encode($document) . '})',
'extensions.MongoYii.EMongoDocument.insert'
);
}
$this->lastError = $this->getCollection()->insert($document, $this->getDbConnection()->getDefaultWriteConcern());
if($this->getDbConnection()->enableProfiling){
Yii::endProfile(
'extensions.MongoYii.EMongoDocument.query.' . $this->collectionName() . '.insert(' . '{$document:' . json_encode($document) . '})',
'extensions.MongoYii.EMongoDocument.insert'
);
}
if($this->lastError){
$this->afterSave();
$this->setIsNewRecord(false);
$this->setScenario('update');
return true;
}
return false;
}
/**
* Updates this record
* @param array $attributes
* @return bool
* @throws EMongoException
* @throws EMongoException
*/
public function update($attributes = null)
{
if($this->getIsNewRecord()){
throw new EMongoException(Yii::t('yii', 'The active record cannot be updated because it is new.'));
}
if(!$this->beforeSave()){
return false;
}
$this->trace(__FUNCTION__);
if($this->getPrimaryKey() === null){ // An _id is required
throw new EMongoException(Yii::t('yii', 'The active record cannot be updated because it has primary key set.'));
}
$partial = false;
if($attributes !== null){
$attributes = $this->filterRawDocument($this->getAttributes($attributes));
$partial = true;
}elseif($this->getIsPartial()){
foreach($this->_projected_fields as $field => $v){
$attributes[$field] = $this->$field;
}
$attributes = $this->filterRawDocument($attributes);
$partial = true;
}else{
$attributes = $this->getRawDocument();
}
if(isset($attributes['_id'])){
unset($attributes['_id']); // Unset the _id before update
}
if($this->versioned()){
$version = $this->{$this->versionField()};
$attributes[$this->versionField()] = $this->{$this->versionField()} = $this->{$this->versionField()} > 0 ? $this->{$this->versionField()} + 1 : 1;
if($partial === true){ // If this is a partial docuemnt we use $set to replace that partial view
$attributes = array('$set' => $attributes);
if(!isset($this->_projected_fields[$this->versionField()])){
// We cannot rely on a partial document containing the version
// as such it has been disabled for partial documents
throw new EMongoException("You cannot update a versioned partial document unless you project out the version field as well");
}
}
$this->lastError = $this->updateAll(
array($this->primaryKey() => $this->getPrimaryKey(), $this->versionField() => $version),
$attributes,
array('multiple' => false)
);
}else{
if($partial === true){ // If this is a partial docuemnt we use $set to replace that partial view
$attributes = array('$set' => $attributes);
}
$this->lastError = $this->updateByPk($this->getPrimaryKey(), $attributes);
}
if($this->versioned() && $this->lastError['n'] <= 0){
return false;
}
$this->afterSave();
return true;
}
/**
* Deletes this record
* @return bool
* @throws EMongoException
*/
public function delete()
{
if($this->getIsNewRecord()){
throw new EMongoException(Yii::t('yii', 'The active record cannot be deleted because it is new.'));
}
$this->trace(__FUNCTION__);
if(!$this->beforeDelete()){
return false;
}
$result = $this->deleteByPk($this->getPrimaryKey());
$this->afterDelete();
return $result;
}
/**
* Checks if a record exists in the database
* @param array $criteria
* @return bool
*/
public function exists($criteria = array())
{
$this->trace(__FUNCTION__);
if($criteria instanceof EMongoCriteria){
$criteria = $criteria->getCondition();
}
return $this->getCollection()->findOne($criteria) !== null;
}
/**
* Compares current active record with another one.
* The comparison is made by comparing table name and the primary key values of the two active records.
* @param EMongoDocument $record - record to compare to
* @return boolean - whether the two active records refer to the same row in the database table.
*/
public function equals($record)
{
return $this->collectionName() === $record->collectionName() && (string)$this->getPrimaryKey() === (string)$record->getPrimaryKey();
}
/**
* Is basically a find one of the last version to be saved
* @return null|EMongoDocument
*/
public function getLatest()
{
$c = $this->find(array($this->primaryKey() => $this->getPrimaryKey()));
if($c->count() <= 0){
return null;
}
foreach($c as $row){
return $this->populateRecord($row);
}
return null;
}
/**
* Find one record
* @param array|EMongoCriteria $criteria
* @param array|string[] $fields
* @return EMongoDocument|null
*/
public function findOne($criteria = array(), $fields = array())
{
$this->trace(__FUNCTION__);
$this->beforeFind(); // Apparently this is applied before even scopes...
if($criteria instanceof EMongoCriteria){
$criteria = $criteria->getCondition();
}
$c = $this->getDbCriteria();
$query = $this->mergeCriteria(isset($c['condition']) ? $c['condition'] : array(), $criteria);
$project = $this->mergeCriteria(isset($c['project']) ? $c['project'] : array(), $fields);
Yii::trace(
'Executing findOne: '.'{$query:' . json_encode($query) . ',$project:' . json_encode($project) . '}',
'extensions.MongoYii.EMongoDocument'
);
if(
$this->getDbConnection()->queryCachingCount > 0
&& $this->getDbConnection()->queryCachingDuration > 0
&& $this->getDbConnection()->queryCacheID !== false
&& ($cache = Yii::app()->getComponent($this->getDbConnection()->queryCacheID))
&& ($cacheKey = 'yii:dbquery'.$this->getDbConnection()->server.':'.$this->getDbConnection()->db .':'.$this->getDbConnection()->getSerialisedQuery($query, $project).':'.$this->getCollection())
&& ($result = $cache->get($cacheKey)) !== false
){
$this->getDbConnection()->queryCachingCount--;
Yii::trace('Query result found in cache', 'extensions.MongoYii.EMongoDocument');
$record = $result[0];
}else{
if($this->getDbConnection()->enableProfiling){
Yii::beginProfile(
'extensions.MongoYii.EMongoDocument.query.' . $this->collectionName() . '.findOne(' . '{$query:' . json_encode($query) . ',$project:' . json_encode($project) . '}' . ')',
'extensions.MongoYii.EMongoDocument.findOne'
);
}
$record = $this->getCollection()->findOne($query, $project);
if($this->getDbConnection()->enableProfiling){
Yii::endProfile(
'extensions.MongoYii.EMongoDocument.query.' . $this->collectionName() . '.findOne(' . '{$query:' . json_encode($query) . ',$project:' . json_encode($project) . '}' . ')',
'extensions.MongoYii.EMongoDocument.findOne'
);
}
if(isset($cache, $cacheKey)){
$cache->set($cacheKey, array($record), $this->getDbConnection()->queryCachingDuration, $this->getDbConnection()->queryCachingDependency);
}
}
$this->resetScope(false);
if($record === null){
return null;
}
return $this->populateRecord($record, true, $project === array() ? false : true);
}
/**
* Find one record, modifies, and returns it.
* @return null|EMongoDocument
*/
public function findAndModify($criteria = array(), $updateDoc = array(), $fields = array(), $options = array())
{
$this->trace(__FUNCTION__);
if ($criteria instanceof EMongoCriteria) {
$criteria = $criteria->getCondition();
}
$c = $this->getDbCriteria();
$criteria = $this->mergeCriteria(isset($c['condition']) ? $c['condition'] : array(), $criteria);
$fields = $this->mergeCriteria(isset($c['project']) ? $c['project'] : array(), $fields);
$options = array_merge($this->getDbConnection()->getDefaultWriteConcern(), $options);
if (YII_DEBUG) {
Yii::trace('Executing findAndModify: { $query: ' . json_encode($criteria) . ', $document: ' . json_encode($updateDoc) . ', $fields: ' . json_encode($fields) . ', $options: ' . json_encode($options) . '}', 'extensions.MongoYii.EMongoDocument');
}
if ($this->getDbConnection()->enableProfiling) {
$token = 'extensions.MongoYii.EMongoDocument.query.' . $this->collectionName() . '.findAndModify({ $query: ' . json_encode($criteria) . ', $document: ' . json_encode($updateDoc) . ', $fields: ' . json_encode($fields) . ', $options: ' . json_encode($options) . '})';
Yii::beginProfile($token, 'extensions.MongoYii.EMongoDocument.findAndModify');
}
$result = $this->getCollection()->findAndModify($criteria, $updateDoc, $fields, $options);
if ($this->getDbConnection()->enableProfiling) {
Yii::enableProfile($token, 'extensions.MongoYii.EMongoDocument.findAndModify');
}
if ($result === null) {
return null;
}
return $this->populateRecord($result, true, $fields === array() ? false : true);
}
/**
* Alias of find
* @param array $criteria
* @param array|string[] $fields
* @return EMongoCursor|EMongoDocument[]
*/
public function findAll($criteria = array(), $fields = array())
{
return $this->find($criteria, $fields);
}
/**
* Alias of find
* @param array $criteria
* @param array|string[] $fields
* @return EMongoCursor|EMongoDocument[]
*/
public function findAllByAttributes($criteria = array(), $fields = array())
{
return $this->find($criteria, $fields);
}
/**
* Finds all records based on $pk
* @param mixed $pk - String, MongoID or array of strings or MongoID values (one can mix strings and MongoID in the array)
* @param array|string[] $fields
* @return EMongoCursor|EMongoDocument[]
* @throws EMongoException
*/
public function findAllByPk($pk, $fields = array())
{
if(is_string($pk) || $pk instanceof MongoId){
return $this->find(array($this->primaryKey() => $this->getPrimaryKey($pk)), $fields);
}
if(!is_array($pk)){
throw new EMongoException(Yii::t('yii', 'Set an incorrect primary key.'));
}
foreach($pk as $key => $value){
$pk[$key] = $this->getPrimaryKey($value);
}
return $this->find(array($this->primaryKey() => array('$in' => $pk)), $fields);
}
/**
* Find some records
* @param array|EMongoCriteria $criteria
* @param array|string[] $fields
* @return EMongoCursor|EMongoDocument[]
*/
public function find($criteria = array(), $fields = array())
{
$this->trace(__FUNCTION__);
$this->beforeFind(); // Apparently this is applied before even scopes...
if($criteria instanceof EMongoCriteria){
$c = $criteria->mergeWith($this->getDbCriteria())->toArray();
$criteria = array();
}else{
$c = $this->getDbCriteria();
}
$query = $this->mergeCriteria(isset($c['condition']) ? $c['condition'] : array(), $criteria);
$project = $this->mergeCriteria(isset($c['project']) ? $c['project'] : array(), $fields);
Yii::trace(
'Executing find: ' . '{$query:'.json_encode($query) . ',$project:'.json_encode($project)
. (isset($c['sort']) ? ',$sort:'.json_encode($c['sort']).',' : '')
. (isset($c['skip']) ? ',$skip:'.json_encode($c['skip']).',' : '')
. (isset($c['limit']) ? ',$limit:'.json_encode($c['limit']).',' : '')
.'}',
'extensions.MongoYii.EMongoDocument'
);
if($this->getDbConnection()->enableProfiling){
$token = 'extensions.MongoYii.EMongoDocument.query.' . $this->collectionName() . '.find(' . '{$query:' . json_encode($query)
. ',$project:'.json_encode($project)
. (isset($c['sort']) ? ',$sort:'.json_encode($c['sort']).',' : '')
. (isset($c['skip']) ? ',$skip:'.json_encode($c['skip']).',' : '')
. (isset($c['limit']) ? ',$limit:'.json_encode($c['limit']).',' : '')
.'})';
Yii::beginProfile($token, 'extensions.MongoYii.EMongoDocument.find');
}
if($c !== array()){
$cursor = new EMongoCursor($this, $query, $project);
if(isset($c['sort'])){
$cursor->sort($c['sort']);
}
if(isset($c['skip'])){
$cursor->skip($c['skip']);
}
if(isset($c['limit'])){
$cursor->limit($c['limit']);
}
$this->resetScope(false);
}else{
$cursor = new EMongoCursor($this, $criteria, $project);
}
if($this->getDbConnection()->enableProfiling){
Yii::endProfile($token, 'extensions.MongoYii.EMongoDocument.find');
}
return $cursor;
}
/**
* Finds one by _id
* @param string|MongoId $_id
* @param array|string[] $fields
* @return EMongoDocument|null
*/
public function findBy_id($_id, $fields = array())
{
$this->trace(__FUNCTION__);
$_id = $this->getPrimaryKey($_id);