forked from sokil/php-mongo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDocument.php
1351 lines (1153 loc) · 36.5 KB
/
Document.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
/**
* This file is part of the PHPMongo package.
*
* (c) Dmytro Sokil <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sokil\Mongo;
use Sokil\Mongo\Document\RelationManager;
use Sokil\Mongo\Document\RevisionManager;
use Sokil\Mongo\Document\InvalidDocumentException;
use Sokil\Mongo\Collection\Definition;
use Sokil\Mongo\Document\OptimisticLockFailureException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use GeoJson\Geometry\Geometry;
/**
* Instance of this class is a representation of one document from collection.
*
* @link https://github.com/sokil/php-mongo#document-schema Document schema
* @link https://github.com/sokil/php-mongo#create-new-document Create new document
* @link https://github.com/sokil/php-mongo#get-and-set-data-in-document get and set data
* @link https://github.com/sokil/php-mongo#storing-document Saving document
* @link https://github.com/sokil/php-mongo#document-validation Validation
* @link https://github.com/sokil/php-mongo#deleting-collections-and-documents Deleting documents
* @link https://github.com/sokil/php-mongo#events Event handlers
* @link https://github.com/sokil/php-mongo#behaviors Behaviors
* @link https://github.com/sokil/php-mongo#relations Relations
*
* @method \Sokil\Mongo\Document onAfterConstruct(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onBeforeValidate(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onAfterValidate(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onValidateError(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onBeforeInsert(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onAfterInsert(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onBeforeUpdate(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onAfterUpdate(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onBeforeSave(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onAfterSave(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onBeforeDelete(callable $handler, int $priority = 0)
* @method \Sokil\Mongo\Document onAfterDelete(callable $handler, int $priority = 0)
*
* @author Dmytro Sokil <[email protected]>
*/
class Document extends Structure
{
const FIELD_TYPE_DOUBLE = 1;
const FIELD_TYPE_STRING = 2;
const FIELD_TYPE_OBJECT = 3;
const FIELD_TYPE_ARRAY = 4;
const FIELD_TYPE_BINARY_DATA = 5;
const FIELD_TYPE_UNDEFINED = 6; // deprecated
const FIELD_TYPE_OBJECT_ID = 7;
const FIELD_TYPE_BOOLEAN = 8;
const FIELD_TYPE_DATE = 9;
const FIELD_TYPE_NULL = 10;
const FIELD_TYPE_REGULAR_EXPRESSION = 11;
const FIELD_TYPE_JAVASCRIPT = 13;
const FIELD_TYPE_SYMBOL = 14;
const FIELD_TYPE_JAVASCRIPT_WITH_SCOPE = 15;
const FIELD_TYPE_INT32 = 16;
const FIELD_TYPE_TIMESTAMP = 17;
const FIELD_TYPE_INT64 = 18;
const FIELD_TYPE_MIN_KEY = 255;
const FIELD_TYPE_MAX_KEY = 127;
/**
*
* @var \Sokil\Mongo\Document\RelationManager
*/
private $relationManager;
const RELATION_HAS_ONE = 'HAS_ONE';
const RELATION_BELONGS = 'BELONGS';
const RELATION_HAS_MANY = 'HAS_MANY';
const RELATION_MANY_MANY = 'MANY_MANY';
/**
*
* @var \Sokil\Mongo\Document\RevisionManager
*/
private $revisionManager;
/**
*
* @var \Sokil\Mongo\Collection
*/
private $collection;
/**
* Name of scenario, used for validating fields
* @var string
*/
private $scenario;
/**
* @var array validator errors
*/
private $errors = array();
/**
* @var array manually added validator errors
*/
private $triggeredErrors = array();
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcher Event Dispatcher instance
*/
private $eventDispatcher;
/**
* @var \Sokil\Mongo\Operator Modification operator instance
*/
private $operator;
/**
*
* @var array list of defined behaviors
*/
private $behaviors = array();
/**
*
* @var array list of namespaces
*/
private $validatorNamespaces = array(
'\Sokil\Mongo\Validator',
);
/**
*
* @var array document options
*/
private $options;
/**
* @param \Sokil\Mongo\Collection $collection instance of Mongo collection
* @param array $data mongo document
* @param array $options options of object initialization
*/
public function __construct(Collection $collection, array $data = null, array $options = array())
{
$this->collection = $collection;
// configure document with options
$this->options = $options;
// init document
$this->initDocument();
// execute before construct callable
$this->beforeConstruct();
// set data
if ($data) {
if ($this->getOption('stored')) {
// load stored
$this->replace($data);
} else {
// create unstored
$this->merge($data);
}
}
// use versioning
if($this->getOption('versioning')) {
$this->getRevisionManager()->listen();
}
// execure after construct event handlers
$this->eventDispatcher->dispatch('afterConstruct');
}
public function getOptions()
{
return $this->options;
}
public function getOption($name, $default = null)
{
return isset($this->options[$name]) ? $this->options[$name] : $default;
}
public function hasOption($name)
{
return isset($this->options[$name]);
}
/**
* Add own namespace of validators
*
* @param type $namespace
* @return \Sokil\Mongo\Document
*/
public function addValidatorNamespace($namespace)
{
$this->validatorNamespaces[] = rtrim($namespace, '\\');
return $this;
}
/**
* Event handler, called before running constructor.
* May be overridden in child classes
*/
public function beforeConstruct()
{
}
/**
* Get instance of collection
* @return \Sokil\Mongo\Collection
*/
public function getCollection()
{
return $this->collection;
}
/**
* Reset all data passed to object in run-time, like events, behaviors,
* data modifications, etc. to the state just after open or save document
*
* @return \Sokil\Mongo\Document
*/
public function reset()
{
// reset structure
parent::reset();
// reset errors
$this->errors = array();
$this->triggeredErrors = array();
// reset behaviors
$this->clearBehaviors();
// init delegates
$this->initDocument();
return $this;
}
/**
* Reload data from db and reset all unsaved data
*/
public function refresh()
{
$data = $this->collection
->getMongoCollection()
->findOne(array(
'_id' => $this->getId()
));
$this->replace($data);
$this->operator->reset();
return $this;
}
/**
* Initialise relative classes
*/
private function initDocument()
{
// start event dispatching
$this->eventDispatcher = new EventDispatcher;
// create operator
$this->operator = $this->getCollection()->operator();
// attach behaviors
$this->attachBehaviors($this->behaviors());
if($this->hasOption('behaviors')) {
$this->attachBehaviors($this->getOption('behaviors'));
}
}
public function __toString()
{
return (string) $this->getId();
}
public function __call($name, $arguments)
{
// behaviors
foreach ($this->behaviors as $behavior) {
if (!method_exists($behavior, $name)) {
continue;
}
return call_user_func_array(array($behavior, $name), $arguments);
}
// adding event
if('on' === substr($name, 0, 2)) {
// prepent ebent name to function args
$addListenerArguments = $arguments;
array_unshift($addListenerArguments, lcfirst(substr($name, 2)));
// add listener
call_user_func_array(
array($this->eventDispatcher, 'addListener'),
$addListenerArguments
);
return $this;
}
// getter
if ('get' === strtolower(substr($name, 0, 3))) {
return $this->get(lcfirst(substr($name, 3)));
}
// setter
if ('set' === strtolower(substr($name, 0, 3)) && isset($arguments[0])) {
return $this->set(lcfirst(substr($name, 3)), $arguments[0]);
}
throw new Exception('Document has no method "' . $name . '"');
}
public function __get($name)
{
if ($this->getRelationManager()->isRelationExists($name)) {
// resolve relation
return $this->getRelationManager()->getRelated($name);
} else {
// get document parameter
return parent::__get($name);
}
}
/**
* Set geo data as GeoJson object
*
* Requires MongoDB version 2.4 or above with 2dsparse index version 1
* to use Point, LineString and Polygon.
*
* Requires MongoDB version 2.6 or above with 2dsparse index version 2
* to use MultiPoint, MultiLineString, MultiPolygon and GeometryCollection.
*
* @link http://geojson.org/
* @param string $field
* @param \GeoJson\Geometry\Geometry $geometry
* @return \Sokil\Mongo\Document
*/
public function setGeometry($field, Geometry $geometry)
{
return $this->set($field, $geometry);
}
/**
* Set point as longitude and latitude
*
* Requires MongoDB version 2.4 or above with 2dsparse index version 1
* to use Point, LineString and Polygon.
*
* @link http://docs.mongodb.org/manual/core/2dsphere/#point
* @param string $field
* @param float $longitude
* @param float $latitude
* @return \Sokil\Mongo\Document
*/
public function setPoint($field, $longitude, $latitude)
{
return $this->setGeometry(
$field,
new \GeoJson\Geometry\Point(array(
$longitude,
$latitude
))
);
}
/**
* Set point as longitude and latitude in legacy format
*
* May be used 2d index
*
* @link http://docs.mongodb.org/manual/core/2d/#geospatial-indexes-store-grid-coordinates
* @param string $field
* @param float $longitude
* @param float $latitude
* @return \Sokil\Mongo\Document
*/
public function setLegacyPoint($field, $longitude, $latitude)
{
return $this->set(
$field,
array($longitude, $latitude)
);
}
/**
* Set line string as array of points
*
* Requires MongoDB version 2.4 or above with 2dsparse index version 1
* to use Point, LineString and Polygon.
*
* @link http://docs.mongodb.org/manual/core/2dsphere/#linestring
* @param string $field
* @param array $pointArray array of points
* @return \Sokil\Mongo\Document
*/
public function setLineString($field, array $pointArray)
{
return $this->setGeometry(
$field,
new \GeoJson\Geometry\LineString($pointArray)
);
}
/**
* Set polygon as array of line rings.
*
* Line ring is closed line string (first and last point same).
* Line string is array of points.
*
* Requires MongoDB version 2.4 or above with 2dsparse index version 1
* to use Point, LineString and Polygon.
*
* @link http://docs.mongodb.org/manual/core/2dsphere/#polygon
* @param string $field
* @param array $lineRingsArray array of line rings
* @return \Sokil\Mongo\Document
*/
public function setPolygon($field, array $lineRingsArray)
{
return $this->setGeometry(
$field,
new \GeoJson\Geometry\Polygon($lineRingsArray)
);
}
/**
* Set multi point as array of points
*
* Requires MongoDB version 2.6 or above with 2dsparse index version 2
* to use MultiPoint, MultiLineString, MultiPolygon and GeometryCollection.
*
* @link http://docs.mongodb.org/manual/core/2dsphere/#multipoint
* @param string $field
* @param array $pointArray array of point arrays
* @return \Sokil\Mongo\Document
*/
public function setMultiPoint($field, $pointArray)
{
return $this->setGeometry(
$field,
new \GeoJson\Geometry\MultiPoint($pointArray)
);
}
/**
* Set multi line string as array of line strings
*
* Requires MongoDB version 2.6 or above with 2dsparse index version 2
* to use MultiPoint, MultiLineString, MultiPolygon and GeometryCollection.
*
* http://docs.mongodb.org/manual/core/2dsphere/#multilinestring
* @param string $field
* @param array $lineStringArray array of line strings
* @return \Sokil\Mongo\Document
*/
public function setMultiLineString($field, $lineStringArray)
{
return $this->setGeometry(
$field,
new \GeoJson\Geometry\MultiLineString($lineStringArray)
);
}
/**
* Set multy polygon as array of polygons.
*
* Polygon is array of line rings.
* Line ring is closed line string (first and last point same).
* Line string is array of points.
*
* Requires MongoDB version 2.6 or above with 2dsparse index version 2
* to use MultiPoint, MultiLineString, MultiPolygon and GeometryCollection.
*
* @link http://docs.mongodb.org/manual/core/2dsphere/#multipolygon
* @param string $field
* @param array $polygonsArray array of polygons
* @return \Sokil\Mongo\Document
*/
public function setMultyPolygon($field, array $polygonsArray)
{
return $this->setGeometry(
$field,
new \GeoJson\Geometry\MultiPolygon($polygonsArray)
);
}
/**
* Set collection of different geometries
*
* Requires MongoDB version 2.6 or above with 2dsparse index version 2
* to use MultiPoint, MultiLineString, MultiPolygon and GeometryCollection.
*
* @link http://docs.mongodb.org/manual/core/2dsphere/#geometrycollection
* @param string $field
* @param array $geometryCollection
* @return \Sokil\Mongo\Document
*/
public function setGeometryCollection($field, array $geometryCollection)
{
return $this->setGeometry(
$field,
new \GeoJson\Geometry\GeometryCollection($geometryCollection)
);
}
/**
* Check if document belongs to specified collection
*
* @deprecated since 1.12.8 Use Collection::hasDocument()
* @param \Sokil\Mongo\Collection $collection collection instance
* @return boolean
*/
public function belongsToCollection(Collection $collection)
{
return $collection->hasDocument($this);
}
/**
* Override in child class to define relations
* @return array relation description
*/
protected function relations()
{
// [relationName => [relationType, targetCollection, reference], ...]
return array();
}
/**
* Relation definition through mapping is more prior to defined in class
* @return array definition of relations
*/
public function getRelationDefinition()
{
$relations = $this->getOption('relations');
if(!is_array($relations)) {
return $this->relations();
}
return $relations + $this->relations();
}
/**
*
* @return \Sokil\Mongo\Document\RelationManager
*/
private function getRelationManager()
{
if($this->relationManager) {
return $this->relationManager;
}
$this->relationManager = new RelationManager($this);
return $this->relationManager;
}
/**
* Get related documents
* @param string $relationName
* @return array|\Sokil\Mongo\Document related document or array of documents
*/
public function getRelated($relationName)
{
return $this->getRelationManager()->getRelated($relationName);
}
public function addRelation($relationName, Document $document)
{
$this->getRelationManager()->addRelation($relationName, $document);
return $this;
}
public function removeRelation($relationName, Document $document = null)
{
$this->getRelationManager()->removeRelation($relationName, $document);
return $this;
}
/**
* Manually trigger defined events
* @param string $eventName event name
* @return \Sokil\Mongo\Event
*/
public function triggerEvent($eventName, Event $event = null)
{
if(!$event) {
$event = new Event;
}
$event->setTarget($this);
return $this->eventDispatcher->dispatch($eventName, $event);
}
/**
* Attach event handler
* @param string $event event name
* @param callable|array|string $handler event handler
* @return \Sokil\Mongo\Document
*/
public function attachEvent($event, $handler, $priority = 0)
{
$this->eventDispatcher->addListener($event, $handler, $priority);
return $this;
}
/**
* Check if event attached
*
* @param string $event event name
* @return bool
*/
public function hasEvent($event)
{
return $this->eventDispatcher->hasListeners($event);
}
public function getId()
{
return $this->get('_id');
}
/**
* Used to define id of stored document. This id must be already present in db
*
* @param \MongoId|string $id id of document
* @return \Sokil\Mongo\Document
*/
public function defineId($id)
{
if ($id instanceof \MongoId) {
$this->_data['_id'] = $id;
return $this;
}
try {
$this->_data['_id'] = new \MongoId($id);
} catch (\MongoException $e) {
$this->_data['_id'] = $id;
}
return $this;
}
/*
* Used to define id of unstored document. This db is manual
*/
public function setId($id)
{
if ($id instanceof \MongoId) {
return $this->set('_id', $id);
}
try {
return $this->set('_id', new \MongoId($id));
} catch (\MongoException $e) {
return $this->set('_id', $id);
}
}
public function isStored()
{
return $this->get('_id') && !$this->isModified('_id');
}
public function setScenario($scenario)
{
$this->scenario = $scenario;
return $this;
}
public function getScenario()
{
return $this->scenario;
}
public function setNoScenario()
{
$this->scenario = null;
return $this;
}
public function isScenario($scenario)
{
return $scenario === $this->scenario;
}
public function rules()
{
return array();
}
private function getValidatorClassNameByRuleName($ruleName)
{
if(false !== strpos($ruleName, '_')) {
$className = implode('', array_map('ucfirst', explode('_', strtolower($ruleName))));
} else {
$className = ucfirst(strtolower($ruleName));
}
foreach ($this->validatorNamespaces as $namespace) {
$fullyQualifiedClassName = $namespace . '\\' . $className . 'Validator';
if (class_exists($fullyQualifiedClassName)) {
return $fullyQualifiedClassName;
}
}
throw new Exception('Validator with name ' . $ruleName . ' not found');
}
/**
* check if filled model params is valid
* @return boolean
*/
public function isValid()
{
$this->errors = array();
foreach ($this->rules() as $rule) {
$fields = array_map('trim', explode(',', $rule[0]));
$ruleName = $rule[1];
$params = array_slice($rule, 2);
// check scenario
if (!empty($rule['on'])) {
$onScenarios = explode(',', $rule['on']);
if (!in_array($this->getScenario(), $onScenarios)) {
continue;
}
}
if (!empty($rule['except'])) {
$exceptScenarios = explode(',', $rule['except']);
if (in_array($this->getScenario(), $exceptScenarios)) {
continue;
}
}
if (method_exists($this, $ruleName)) {
// method
foreach ($fields as $field) {
$this->{$ruleName}($field, $params);
}
} else {
// validator class
$validatorClassName = $this->getValidatorClassNameByRuleName($ruleName);
/* @var $validator \Sokil\Mongo\Validator */
$validator = new $validatorClassName;
if (!$validator instanceof \Sokil\Mongo\Validator) {
throw new Exception('Validator class must implement \Sokil\Mongo\Validator class');
}
$validator->validate($this, $fields, $params);
}
}
return !$this->hasErrors();
}
/**
*
* @throws \Sokil\Mongo\Document\InvalidDocumentException
* @return \Sokil\Mongo\Document
*/
public function validate()
{
if($this->triggerEvent('beforeValidate')->isCancelled()) {
return $this;
}
if (!$this->isValid()) {
$exception = new InvalidDocumentException('Document not valid');
$exception->setDocument($this);
$this->triggerEvent('validateError');
throw $exception;
}
$this->triggerEvent('afterValidate');
return $this;
}
public function hasErrors()
{
return ($this->errors || $this->triggeredErrors);
}
/**
* get list of validation errors
*
* Format: $errors['fieldName']['rule'] = 'message';
*
* @return array list of validation errors
*/
public function getErrors()
{
return array_merge_recursive($this->errors, $this->triggeredErrors);
}
/**
* Add validator error from validator classes and methods. This error
* reset on every revalidation
*
* @param string $fieldName dot-notated field name
* @param string $ruleName name of validation rule
* @param string $message error message
* @return \Sokil\Mongo\Document
*/
public function addError($fieldName, $ruleName, $message)
{
$this->errors[$fieldName][$ruleName] = $message;
// Deprecated. Related to bug when suffix not removed from class.
// Added for back compatibility and will be removed in next versions
$this->errors[$fieldName][$ruleName . 'validator'] = $message;
return $this;
}
/**
* Add errors
*
* @param array $errors
* @return \Sokil\Mongo\Document
*/
public function addErrors(array $errors)
{
$this->errors = array_merge_recursive($this->errors, $errors);
return $this;
}
/**
* Add custom error which not reset after validation
*
* @param type $fieldName
* @param type $ruleName
* @param type $message
* @return \Sokil\Mongo\Document
*/
public function triggerError($fieldName, $ruleName, $message)
{
$this->triggeredErrors[$fieldName][$ruleName] = $message;
return $this;
}
/**
* Add custom errors
*
* @param array $errors
* @return \Sokil\Mongo\Document
*/
public function triggerErrors(array $errors)
{
$this->triggeredErrors = array_merge_recursive($this->triggeredErrors, $errors);
return $this;
}
/**
* Remove custom errors
*
* @return \Sokil\Mongo\Document
*/
public function clearTriggeredErrors()
{
$this->triggeredErrors = array();
return $this;
}
public function behaviors()
{
return array();
}
public function attachBehaviors(array $behaviors)
{
foreach ($behaviors as $name => $behavior) {
$this->attachBehavior($name, $behavior);
}
return $this;
}
/**
*
* @param string $name unique name of attached behavior
* @param string|array|\Sokil\Mongo\Behavior $behavior Behavior instance or behavior definition
* @return \Sokil\Mongo\Document
* @throws Exception
*/
public function attachBehavior($name, $behavior)
{
if(is_string($behavior)) {
// behavior defined as string
$className = $behavior;
$behavior = new $className();
} elseif(is_array($behavior)) {
// behavior defined as array
if (empty($behavior['class'])) {
throw new Exception('Behavior class not specified');
}
$className = $behavior['class'];
unset($behavior['class']);
$behavior = new $className($behavior);
} elseif (!($behavior instanceof Behavior)) {
// behavior bust be Behavior instance, but something else found
throw new Exception('Wrong behavior specified with name ' . $name);
}
$behavior->setOwner($this);
$this->behaviors[$name] = $behavior;
return $this;
}
public function clearBehaviors()
{
$this->behaviors = array();
return $this;
}
public function getOperator()
{
return $this->operator;
}
public function isModificationOperatorDefined()
{
return $this->operator->isDefined();
}
/**
* Update value in local cache and in DB
*
* @param string $fieldName point-delimited field name
* @param mixed $value value to store
* @return \Sokil\Mongo\Document
*/
public function set($fieldName, $value)
{
parent::set($fieldName, $value);
// if document saved - save through update
if ($this->getId()) {
$this->operator->set($fieldName, $value);
}
return $this;
}
/**
* Remove field
*
* @param string $fieldName field name
* @return \Sokil\Mongo\Document
*/
public function unsetField($fieldName)
{
if (!$this->has($fieldName)) {
return $this;
}
parent::unsetField($fieldName);
if ($this->getId()) {
$this->operator->unsetField($fieldName);
}
return $this;
}
public function __unset($fieldName)
{
$this->unsetField($fieldName);
}
public function merge(array $data)
{