This repository has been archived by the owner on Oct 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDocument.php
1922 lines (1725 loc) · 68.3 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
namespace ext\activedocument;
use \Yii,
\CModel,
\CEvent,
\ext\activedocument\events\Event;
Yii::import('ext.activedocument.Relation', true);
/**
* Document
*
* @property \ext\activedocument\Document $owner
* @property \ext\activedocument\Object $object
* @property bool $isNewRecord
* @property \ext\activedocument\Criteria $criteria
* @property mixed $primaryKey
* @property-read bool $isModified
* @property-read string $encodedPk
* @property-read \ext\activedocument\Connection $connection
* @property-read \ext\activedocument\Adapter $adapter
* @property-read string $containerName
* @property-read \ext\activedocument\Container $container
* @property-read \ext\activedocument\MetaData $metaData
*/
abstract class Document extends CModel {
const BELONGS_TO = '\ext\activedocument\BelongsToRelation';
const HAS_ONE = '\ext\activedocument\HasOneRelation';
const HAS_MANY = '\ext\activedocument\HasManyRelation';
const MANY_MANY = '\ext\activedocument\ManyManyRelation';
const STAT = '\ext\activedocument\StatRelation';
/**
* Override with component connection name, if not 'conn'
* Is accessed using Late Static Binding (i.e. - static::$connName)
*
* @var string
*/
public static $connName = 'conn';
/**
* Array of connections
*
* @var \ext\activedocument\Connection[]
*/
public static $connections = array();
private static $_models = array();
protected $_related = array();
/**
* @var \ext\activedocument\MetaData
*/
private $_md;
/**
* @var \ext\activedocument\Criteria
*/
private $_c;
/**
* @var \ext\activedocument\Container
*/
protected $_container;
/**
* @var \ext\activedocument\Object
*/
protected $_object;
protected $_new = false;
protected $_attributes = array();
protected $_pk;
/**
* The columns that have been modified in current object.
* Tracking modified columns allows us to only update modified columns.
*
* @var array
*/
protected $_modifiedAttributes = array();
/**
* @var \ext\activedocument\Document
*/
protected $_owner;
/**
* @static
*
* @param string $className optional
*
* @return \ext\activedocument\Document
*/
public static function model($className = null) {
if ($className === null)
$className = get_called_class();
if (isset(self::$_models[$className]))
return self::$_models[$className];
else {
/**
* @var \ext\activedocument\Document $document
*/
$document = self::$_models[$className] = new $className(null);
$document->_md = new MetaData($document);
$document->attachBehaviors($document->behaviors());
return $document;
}
}
public function __construct($scenario = 'insert') {
if ($scenario === null)
return;
$this->setScenario($scenario);
$this->setIsNewRecord(true);
$this->newObject();
$this->init();
$this->attachBehaviors($this->behaviors());
$this->afterConstruct();
}
public function init() {
/**
* Replacing certain validators
*/
\CValidator::$builtInValidators = array_merge(\CValidator::$builtInValidators, array(
'unique' => '\ext\activedocument\validators\Unique',
));
$this->resetModified();
return $this;
}
/**
* The owner/parent of this Document (if any)
*
* @return \ext\activedocument\Document
*/
public function getOwner() {
return $this->_owner;
}
/**
* The owner/parent of this Document (if any)
*
* @param Document|null $owner
*
* @return Document
*/
public function setOwner(Document $owner = null) {
$this->_owner = $owner;
return $this;
}
/**
* @return Document
*/
protected function newObject() {
$this->setObject($this->loadObject());
return $this;
}
/**
* @param null $key
*
* @return Object
*/
protected function loadObject($key = null) {
return $this->getContainer()->getObject($key, null, $this->getIsNewRecord());
}
/**
* @return Object
*/
public function getObject() {
return $this->_object;
}
/**
* @param Object $object
*
* @return Document
*/
public function setObject(Object $object) {
$this->_object = $object;
if (!$this->getIsNewRecord()) {
$this->setAttributes($this->_object->data, false);
$this->ensurePk();
} else {
$this->_object->data = $this->getMetaData()->attributeDefaults;
$this->setAttributes($this->_object->data, false);
}
return $this;
}
/**
* @return bool
*/
public function getIsNewRecord() {
return $this->_new;
}
/**
* @param bool $value
*
* @return Document
*/
public function setIsNewRecord($value) {
$this->_new = $value;
return $this;
}
/**
* Returns whether the object has been modified.
*
* @return boolean True if the object has been modified.
*/
public function getIsModified() {
return $this->getModifiedAttributes()!==array();
}
/**
* Has specified attribute been modified?
*
* @param string $attr attribute fully qualified name
*
* @return boolean True if $attr has been modified.
*/
public function isAttributeModified($attr) {
return in_array($attr, $this->getModifiedAttributes());
}
/**
* Get the attributes that have been modified in this object.
*
* @return array A unique list of the modified attribute names for this object.
*/
public function getModifiedAttributes() {
return array_unique(
array_merge(
$this->_modifiedAttributes, array_keys(
array_diff_assoc(
array_intersect_key($this->getObject()->data, $this->getMetaData()->getAttributes(true)),
$this->getAttributes()
)
)
)
);
}
/**
* Sets the modified state for the object to be false.
*
* @param string $attr If supplied, only the specified attribute is reset.
*
* @return Document
*/
public function resetModified($attr = null) {
if ($attr !== null) {
while (($offset = array_search($attr, $this->_modifiedAttributes)) !== false) {
array_splice($this->_modifiedAttributes, $offset, 1);
}
} else {
$this->_modifiedAttributes = array();
}
return $this;
}
/**
* @param bool $createIfNull
*
* @return Criteria
*/
public function getCriteria($createIfNull = true) {
if ($this->_c === null) {
if (($c = $this->defaultScope()) !== array() || $createIfNull)
$this->_c = new Criteria($c);
}
return $this->_c;
}
/**
* @param Criteria $criteria
*
* @return Document
*/
public function setCriteria($criteria) {
$this->_c = $criteria;
return $this;
}
/**
* @return array
*/
public function defaultScope() {
return array();
}
/**
* @return Document
*/
public function resetScope() {
$this->_c = new Criteria();
return $this;
}
/**
* @return array
*/
public function __sleep() {
$this->_md = null;
return array_keys((array)$this);
}
public function &__get($name) {
if (isset($this->_attributes[$name]))
return $this->_attributes[$name];
else if (isset($this->getMetaData()->attributes->$name)) {
$return = null;
return $return;
} else if (isset($this->_related[$name]))
return $this->_related[$name];
else if (isset($this->getMetaData()->relations->$name))
return $this->getRelated($name);
else {
if ((strncasecmp($name, 'on', 2) !== 0 || !$this->hasEvent($name)) && !method_exists($this, 'get' . $name) &&
$this->hasEvent('onGetMissingAttribute') && $this->getEventHandlers('onGetMissingAttribute')
->getCount() > 0
) {
$this->onGetMissingAttribute($event = new events\Magic($this, events\Magic::GET, $name));
if ($event->handled)
return $event->result;
}
$return = parent::__get($name);
return $return;
}
}
public function __set($name, $value) {
if ($this->setAttribute($name, $value) === false) {
if (isset($this->getMetaData()->relations->$name)) {
$this->_related[$name] = $value;
$this->_modifiedAttributes[] = $name;
} else {
if ((strncasecmp($name, 'on', 2) !== 0 || !$this->hasEvent($name)) && !method_exists($this, 'set' . $name) &&
$this->hasEvent('onSetMissingAttribute') && $this->getEventHandlers('onSetMissingAttribute')
->getCount() > 0
) {
$this->onSetMissingAttribute($event = new events\Magic($this, events\Magic::SET, $name, $value));
if ($event->handled)
return $event->result;
}
parent::__set($name, $value);
}
}
}
public function __isset($name) {
if (isset($this->_attributes[$name]))
return true;
else if (isset($this->getMetaData()->attributes->$name))
return false;
else if (isset($this->_related[$name]))
return true;
else if (isset($this->getMetaData()->relations->$name))
return $this->getRelated($name) !== null;
else {
if ((strncasecmp($name, 'on', 2) !== 0 || !$this->hasEvent($name)) && !method_exists($this, 'get' . $name) &&
$this->hasEvent('onIssetMissingAttribute') && $this->getEventHandlers('onIssetMissingAttribute')
->getCount() > 0
) {
$this->onIssetMissingAttribute($event = new events\Magic($this, events\Magic::SETIS, $name));
if ($event->handled)
return $event->result;
}
return parent::__isset($name);
}
}
public function __unset($name) {
if (isset($this->getMetaData()->attributes->$name)) {
unset($this->_attributes[$name]);
$this->_modifiedAttributes[] = $name;
} else if (isset($this->getMetaData()->relations->$name)) {
unset($this->_related[$name]);
$this->_modifiedAttributes[] = $name;
} else {
if ((strncasecmp($name, 'on', 2) !== 0 || !$this->hasEvent($name)) && !method_exists($this, 'set' . $name) &&
$this->hasEvent('onUnsetMissingAttribute') && $this->getEventHandlers('onUnsetMissingAttribute')
->getCount() > 0
) {
$this->onUnsetMissingAttribute($event = new events\Magic($this, events\Magic::SETUN, $name));
if ($event->handled)
return $event->result;
}
parent::__unset($name);
}
}
public function __call($name, $parameters) {
if (isset($this->getMetaData()->relations->$name)) {
if (empty($parameters))
return $this->getRelated($name, false);
elseif (isset($parameters[0]) && isset($parameters[1]))
return $this->getRelated($name, false, $parameters[0], $parameters[1]);
elseif (isset($parameters[0]))
return $this->getRelated($name, false, $parameters[0]);
}
$scopes = $this->scopes();
if (isset($scopes[$name])) {
$this->getCriteria()->mergeWith($scopes[$name]);
return $this;
}
if ((strncasecmp($name, 'on', 2) !== 0 || !$this->hasEvent($name)) && $this->hasEvent('onCallMissingMethod')
&& $this->getEventHandlers('onCallMissingMethod')->getCount() > 0
) {
$this->onCallMissingMethod($event = new events\Magic($this, events\Magic::CALL, $name, $parameters));
if ($event->handled)
return $event->result;
}
return parent::__call($name, $parameters);
}
public function onGetMissingAttribute(events\Magic $event) {
$this->raiseEvent('onGetMissingAttribute', $event);
}
public function onSetMissingAttribute(events\Magic $event) {
$this->raiseEvent('onSetMissingAttribute', $event);
}
public function onIssetMissingAttribute(events\Magic $event) {
$this->raiseEvent('onIssetMissingAttribute', $event);
}
public function onUnsetMissingAttribute(events\Magic $event) {
$this->raiseEvent('onUnsetMissingAttribute', $event);
}
public function onCallMissingMethod(events\Magic $event) {
$this->raiseEvent('onCallMissingMethod', $event);
}
/**
* Returns arrays of indexed keys, only applicable to HasMany or ManyMany relations
*
* @param string $name The relation name (see {@link relations})
* @param string|array $index Name of the index, or array of index names
*
* @return array[]array[]string
*/
public function getRelatedKeysByIndexName($name, $index) {
$index = array_combine((array)$index, (array)$index);
$object = $this->getObject();
$relation = $this->getMetaData()->relations[$name];
return array_map(function($index) use($name, $object, $relation) {
return isset($object->data[$name . '_' . $index]) ?
array_map(function($key)use($relation){
return Document::model($relation->className)->typecastPk($key);
}, $object->data[$name . '_' . $index]) :
array();
}, $index);
}
/**
* Return array of keys, filtered by specified index values, only applicable to HasMany or ManyMany relations
*
* @param string $name The relation name (see {@link relations})
* @param array $indexes Array of 'indexName'=>'searchValue' to search by
* @param array $keys Array of keys to additionally filter by
*
* @return array
*/
public function getRelatedKeysByIndex($name, array $indexes, array $keys = array()) {
$pks = array();
$object = $this->getObject();
$class = get_class($this);
$relation = $this->getMetaData()->relations[$name];
array_walk($indexes, function($indexValue, $index) use($name, $object, &$pks, $class) {
$indexName = $name . '_' . $index;
if ($indexValue === '' || $indexValue === null)
return;
/**
* @var Document $class
*/
$indexValue = $class::stringify($indexValue);
if (!isset($object->data[$indexName][$indexValue]) || $object->data[$indexName][$indexValue] === array())
return;
$pks[] = $object->data[$indexName][$indexValue];
});
if ($pks === array())
return array();
/**
* @todo Move this to a class method
*/
$typecastPks = function($key)use($relation){
return Document::model($relation->className)->typecastPk($key);
};
$pks = array_map($typecastPks, $pks);
if ($keys !== array())
array_push($pks, array_map($typecastPks, $keys));
return count($pks) > 1 ? call_user_func_array('array_intersect', $pks) : array_shift($pks);
}
/**
* @param string $name Relation name
* @return array|mixed|null
*/
public function getRelatedKeys($name) {
$relation = $this->getMetaData()->relations[$name];
if (!isset($this->getObject()->data[$name]) || !($relation instanceof Relation))
return null;
if ($relation instanceof HasManyRelation) {
if ($relation->nested === true)
return array_map(function(Document $obj){
return $obj->getPrimaryKey();
}, $this->getRelated($name));
else
return array_map(function($key)use($relation){
return Document::model($relation->className)->typecastPk($key);
}, $this->getObject()->data[$name]);
} else {
if ($relation->nested === true) {
if (($obj = $this->getRelated($name)))
/**
* @var Document $obj
*/
return $obj->getPrimaryKey();
} else
return Document::model($relation->className)->typecastPk($this->getObject()->data[$name]);
}
return null;
}
/**
* Returns related records filtered by indexed values, only applicable to HasMany or ManyMany relations
*
* @param string $name The relation name (see {@link relations})
* @param array $indexes Array of 'indexName'=>'searchValue' to search by
* @param bool $refresh Whether to force reload objects from db
* @param array|Criteria $criteria Additional parameters to customize query
* @param array $keys Array of keys to additionally filter by
*
* @return array
*/
public function &getRelatedByIndex($name, array $indexes, $refresh = false, $criteria = array(), array $keys = array()) {
$pks = $this->getRelatedKeysByIndex($name, $indexes, $keys);
if ($pks === array())
return $pks;
Yii::trace('Requesting related records for relation ' . get_class($this) . '.' . $name . ', filtered by ' . \CVarDumper::dumpAsString($indexes), 'ext.activedocument.document.getRelatedByIndex');
$related = $this->getRelated($name, $refresh, $criteria, $pks);
return $related;
}
/**
* Returns the related record(s).
* This method will return the related record(s) of the current record.
* If the relation is HAS_ONE or BELONGS_TO, it will return a single object
* or null if the object does not exist.
* If the relation is HAS_MANY or MANY_MANY, it will return an array of objects
* or an empty array.
*
* @param string $name the relation name (see {@link relations})
* @param boolean $refresh Optional whether to reload the related objects from database. Defaults to false.
* @param array|Criteria $criteria Optional criteria to customize the relation query.
* @param array $keys Optional Array of encoded primary keys to filter by on HasMany or ManyMany relations
*
* @return mixed the related object(s).
* @throws Exception if the relation is not specified in {@link relations}.
*/
public function &getRelated($name, $refresh = false, $criteria = array(), array $keys = array()) {
if ($keys !== array() && isset($this->getMetaData()->relations[$name]))
$keys = array_combine(array_map(array('self','stringify'), $keys),
array_map(array(Document::model($this->getMetaData()->relations[$name]->className), 'typecastPk'), $keys));
if (!$refresh && $criteria === array() && (isset($this->_related[$name]) || array_key_exists($name, $this->_related))) {
if ($keys !== array() && is_array($this->_related[$name])) {
$related = array_filter($this->_related[$name], function(Document $document) use($keys) {
return in_array($document->getPrimaryKey(), $keys, true);
});
return $related;
} else {
return $this->_related[$name];
}
}
$md = $this->getMetaData();
if (!isset($md->relations[$name]))
throw new Exception(Yii::t('yii', '{class} does not have relation "{name}".', array('{class}' => get_class($this), '{name}' => $name)));
Yii::trace('lazy loading ' . get_class($this) . '.' . $name, 'ext.activedocument.document.getRelated');
/**
* @var BaseRelation $relation
*/
$relation = $md->relations[$name];
if ($this->getIsNewRecord() && !$refresh && ($relation instanceof HasOneRelation || $relation instanceof HasManyRelation)) {
$_r = $relation instanceof HasOneRelation ? null : array();
return $_r;
}
if ($criteria !== array() || ($relation instanceof HasManyRelation && $keys !== array())) { // dynamic query
$exists = $this->hasRelated($name);
if ($exists)
$save = $this->_related[$name];
}
unset($this->_related[$name]);
$data = $this->getObject()->data;
if (isset($data[$name])) {
$finder = Document::model($relation->className);
$finder->resetScope();
if ($relation instanceof Relation && $relation->nested === true && $criteria === array()) {
Yii::trace('Loading nested ' . get_class($this) . '.' . $name, 'ext.activedocument.document.getRelated');
if ($relation instanceof HasManyRelation) {
if ($keys !== array())
$data[$name] = array_intersect_key($data[$name], $keys);
array_walk($data[$name], function(&$rel, $key) use($finder) {
/**
* @var Document $finder
*/
$rel = $finder->getContainer()->getObject(null, $rel, true);
});
$this->_related[$name] = $finder->populateDocuments($data[$name]);
} else
/**
* @todo Need to verify that this solution works consistently...
*/
$this->_related[$name] = $finder->populateDocument(
$finder->getContainer()->getObject(null, $data[$name], true)
);
} else {
if ($relation instanceof HasManyRelation) {
if ($relation->nested === true) {
if ($keys !== array())
$data[$name] = array_intersect_key($data[$name], $keys);
$pks = array_map(function($rel)use($finder){
/**
* @var Document $finder
*/
$obj = $finder->populateDocument(
$finder->getContainer()->getObject(null, $rel, true)
);
if ($obj!==null)
return $obj->getPrimaryKey();
return false;
}, $data[$name]);
} else {
$pks = $data[$name];
if ($keys !== array())
$pks = array_intersect_key($data[$name], $keys);
}
$this->_related[$name] = $finder->findAllByPk(array_filter($pks), $criteria);
} elseif ($relation instanceof StatRelation) {
$this->_related[$name] = $finder->count($criteria);
} else {
if ($relation->nested === true) {
/**
* @todo Need to verify that this solution works consistently...
*/
$obj = $finder->populateDocument(
$finder->getContainer()->getObject(null, $data[$name], true)
);
if ($obj !== null)
$this->_related[$name] = $finder->findByPk($obj->getPrimaryKey(), $criteria);
} else {
$this->_related[$name] = $finder->findByPk($data[$name], $criteria);
}
}
}
}
if (!isset($this->_related[$name])) {
if ($relation instanceof HasManyRelation)
$this->_related[$name] = array();
else if ($relation instanceof StatRelation)
$this->_related[$name] = $relation->defaultValue;
else
$this->_related[$name] = null;
}
if ($criteria !== array() || ($relation instanceof HasManyRelation && $keys !== array())) {
$results = $this->_related[$name];
if ($exists)
$this->_related[$name] = $save;
else
unset($this->_related[$name]);
return $results;
}
else
return $this->_related[$name];
}
/**
* Returns a value indicating whether the named related object(s) has been loaded.
*
* @param string $name the relation name
*
* @return boolean a value indicating whether the named related object(s) has been loaded.
*/
public function hasRelated($name) {
return isset($this->_related[$name]) || array_key_exists($name, $this->_related);
}
/**
* Used to populate related objects. This method adds a related object to this record.
*
* @param string $name attribute name
* @param array|Document $document the related document[s]
* @param string $foreignName the name of this relationship in the related document. If not empty, relation will be set both ways
*/
public function addRelated($name, $document, $foreignName = null) {
if ($this->getMetaData()->relations->$name instanceof HasManyRelation && !is_array($document)) {
if (!isset($this->_related[$name]) || !is_array($this->_related[$name]))
$this->_related[$name] = array();
$this->_related[$name][] = $document;
} else
$this->_related[$name] = $document;
$this->_modifiedAttributes[] = $name;
if (!empty($foreignName)) {
if (!is_array($document))
$document = array($document);
array_walk($document, function(Document $document, $index, array $relation) {
list($relationName, $relatedDocument) = $relation;
$document->addRelated($relationName, $relatedDocument);
}, array($foreignName, $this));
}
}
public function hasAttribute($name) {
return isset($this->getMetaData()->attributes->$name);
}
public function getAttribute($name) {
if (property_exists($this, $name))
return $this->$name;
else if (isset($this->_attributes[$name]))
return $this->_attributes[$name];
}
public function setAttribute($name, $value) {
if (property_exists($this, $name))
$this->$name = $this->typecastAttribute($name, $value);
else if (isset($this->getMetaData()->attributes->$name)) {
$this->_attributes[$name] = $this->typecastAttribute($name, $value);
} else
return false;
$this->_modifiedAttributes[] = $name;
return true;
}
public function typecastAttribute($name, $value) {
if (isset($this->getMetaData()->attributes->$name)) {
/**
* Typecast the value
*/
if ($value !== null && $value !== '' && ($type = $this->getMetaData()->attributes->$name->type))
settype($value, $type);
}
return $value;
}
public function typecastPk($key) {
$pk = $this->primaryKey();
if ($pk === '_pk')
return $key;
if (is_string($pk))
$key = $this->typecastAttribute($pk, $key);
else {
foreach ($pk as $pkField) {
if (isset($key[$pkField]) && $key[$pkField]!=='')
$key[$pkField] = $this->typecastAttribute($pkField, $key[$pkField]);
}
}
return $key;
}
public function getAttributes($names = true) {
$attributes = $this->_attributes;
foreach ($this->attributeNames() as $name) {
if (property_exists($this, $name))
$attributes[$name] = $this->$name;
else if ($names === true && !isset($attributes[$name]))
$attributes[$name] = null;
}
if (is_array($names)) {
$attrs = array();
foreach ($names as $name) {
if (property_exists($this, $name))
$attrs[$name] = $this->$name;
else
$attrs[$name] = isset($attributes[$name]) ? $attributes[$name] : null;
}
return $attrs;
}
else
return $attributes;
}
/**
* 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
*
* @return mixed
*/
public function setAttributes($values, $safeOnly = true) {
if (!is_array($values))
return;
/**
* @todo Intersect keys from $values against attribute names, to properly mark attributes as modified
*/
$this->_modifiedAttributes += $safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames();
return parent::setAttributes($values, $safeOnly);
}
public function refresh() {
Yii::trace(get_class($this) . '.refresh()', 'ext.activedocument.Document');
if (!$this->getIsNewRecord() && $this->getObject()->reload()) {
$this->_related = array();
$object = $this->getObject();
foreach ($this->getMetaData()->attributes as $name => $attr) {
if (property_exists($this, $name) && isset($object->data[$name]))
$this->$name = $object->data[$name];
}
$this->resetModified();
return true;
}
else
return false;
}
public function equals(Document $document) {
return $this->getContainerName() === $document->getContainerName() && $this->getPrimaryKey() === $document->getPrimaryKey();
}
/**
* Returns the propert[y|ies] used to compose the model pk
*
* @return string|array
*/
public function primaryKey() {
return '_pk';
}
/**
* Returns the model's pk value
*
* @return mixed
*/
public function getPrimaryKey() {
$pk = $this->primaryKey();
if (is_string($pk))
return $this->{$pk};
else {
$return = array();
foreach ($pk as $pkField) {
if (!isset($this->{$pkField}) || $this->{$pkField} === '')
return null;
$return[$pkField] = $this->{$pkField};
}
return $return;
}
}
public function setPrimaryKey($value) {
if ($this->primaryKey() !== '_pk')
throw new Exception('Unable to store custom primary key!');
$this->_pk = $value;
}
/**
* Method to ensure that $this->_pk is defined correctly
*/
protected function ensurePk() {
if ($this->primaryKey()!=='_pk') {
$pk = $this->getPrimaryKey();
if (($pk=$this->getPrimaryKey()) !== null)
$pk = $this->typecastPk($pk);
$this->_pk = $pk;
} elseif ($this->_pk === null && $this->_object->getKey() !== null) {
$this->_pk = $this->_object->getKey();
}
}
/**
* @return string
*/
public function getEncodedPk() {
$this->ensurePk();
return ($this->_pk===null ? null : self::stringify($this->_pk));
}
/**
* Self-recursive function (for arrays)
* Takes mixed variable types
* Returns objects/arrays as json
* Casts any other type to string to ensure type consistency
*
* @param mixed $var
*
* @return string
*/
public static function stringify($var) {
if (is_array($var)) {
/**
* Sort by key to ensure consistent output
*/
ksort($var);
return \CJSON::encode(array_map(array('self', 'stringify'), $var));
}
if (is_object($var) && !(method_exists($var, '__toString')))
return \CJSON::encode($var);
/**
* Test for int numbers, ensure storage as string
*/
if (is_numeric($var) && is_int($var+0) && substr_compare($var, 0, 0, 1)!==0)
return '0'.strval($var);
return \CPropertyValue::ensureString($var);
}
/* public function cache($duration, $dependency=null, $queryCount=1) {
$this->getDbConnection()->cache($duration, $dependency, $queryCount);
return $this;
} */
/**
* @todo Implement support for indexing at bucket level
* @return array
*/
public function indexes() {
return array();
}
public function relations() {
return array();
}
public function scopes() {
return array();
}
public function attributeNames() {
return array_keys((array)$this->getMetaData()->attributes);
}
/**
* Defines validation ruleset for models, override to prevent automatic rule generation.
*
* @todo Define rules based on attribute types
*
* @return array
*/
public function rules() {
return array_merge(parent::rules(), array(
array(implode(', ', $this->attributeNames()), 'safe', 'on' => 'search'),
));
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* @param array $attributes Array of attribute names to limit searching to
*
* @return \ext\activedocument\DataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search(array $attributes = array()) {
$criteria = new Criteria;
$attributes = array_intersect_key((array)$this->getMetaData()->attributes, array_flip(!empty($attributes) ? $attributes : $this->getSafeAttributeNames()));
foreach ($attributes as $name => $attribute) {
if ($attribute->type === 'string')
$criteria->compare($name, $this->$name, true);
else
$criteria->compare($name, $this->$name);
}
return new DataProvider(get_class($this), array(
'criteria' => $criteria,
));
}
/**
* @return \ext\activedocument\Connection
*/