speakplace /library/Shanty/Mongo/Document.php

Language PHP Lines 1263
MD5 Hash 7a8d6557bad537fc1fffac6c22d15891 Estimated Cost $17,882 (why?)
Repository https://bitbucket.org/ilyabazhenov/speakplace View Raw File View Project SPDX
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
<?php
require_once 'Shanty/Mongo/Exception.php';
require_once 'Shanty/Mongo/Collection.php';
require_once 'Shanty/Mongo/Iterator/Default.php';

/**
 * @category   Shanty
 * @package    Shanty_Mongo
 * @copyright  Shanty Tech Pty Ltd
 * @license    New BSD License
 * @author     Coen Hyde
 */
class Shanty_Mongo_Document extends Shanty_Mongo_Collection implements ArrayAccess, Countable, IteratorAggregate
{
	protected static $_requirements = array(
		'_id' => 'Validator:MongoId',
		'_type' => 'Array'
	);
	
	protected $_docRequirements = array();
	protected $_data = array();
	protected $_cleanData = array();
	protected $_config = array(
		'new' => true,
		'connectionGroup' => null,
		'db' => null,
		'collection' => null,
		'pathToDocument' => null,
		'criteria' => array(),
		'parentIsDocumentSet' => false,
		'requirementModifiers' => array(),
		'locked' => false
	);
	protected $_operations = array();
	protected $_references = null;
	
	public function __construct($data = array(), $config = array())
	{
		// Make sure mongo is initialised
		Shanty_Mongo::init();
		
		$this->_config = array_merge($this->_config, $config);
		$this->_references = new SplObjectStorage();

		// If not connected and this is a new root document, figure out the db and collection
		if ($this->isNewDocument() && $this->isRootDocument() && !$this->isConnected()) {
			$this->setConfigAttribute('connectionGroup', static::getConnectionGroupName());
			$this->setConfigAttribute('db', static::getDbName());
			$this->setConfigAttribute('collection', static::getCollectionName());
		}
		
		// Get collection requirements
		$this->_docRequirements = static::getCollectionRequirements();
		
		// apply requirements requirement modifiers
		$this->applyRequirements($this->_config['requirementModifiers'], false);

		// Store data
		$this->_cleanData = $data;

		// Initialize input data
		if ($this->isNewDocument() && is_array($data)) {
			foreach ($data as $key => $value) {
				$this->getProperty($key);
			}
		}

		// Create document id if one is required
		if ($this->isNewDocument() && ($this->hasKey() || (isset($this->_config['hasId']) && $this->_config['hasId']))) {
			$this->_data['_id'] = new MongoId();
			$this->_data['_type'] = static::getCollectionInheritance();
		}
		
		// If has key then add it to the update criteria
		if ($this->hasKey()) {
			$this->setCriteria($this->getPathToProperty('_id'), $this->getId());
		}
		
		$this->init();
	}
	
	protected function init()
	{
		
	}
	
	protected function preInsert()
	{
		
	}
	
	protected function postInsert()
	{
		
	}
	
	protected function preUpdate()
	{
		
	}
	
	protected function postUpdate()
	{
		
	}
	
	protected function preSave()
	{
		
	}
	
	protected function postSave()
	{
		
	}
	
	protected function preDelete()
	{
		
	}
	
	protected function postDelete()
	{
		
	}
	
	/**
	 * Get this document's id
	 * 
	 * @return MongoId
	 */
	public function getId()
	{
		return $this->_id;
	}
	
	/**
	 * Does this document have an id
	 * 
	 * @return boolean
	 */
	public function hasId()
	{
		return !is_null($this->getId());
	}
	
	/**
	 * Get the inheritance of this document
	 * 
	 * @return array
	 */
	public function getInheritance()
	{
		return $this->_type;
	}
	
	/**
	 * Get a config attribute
	 * 
	 * @param string $attribute
	 */
	public function getConfigAttribute($attribute)
	{
		if (!$this->hasConfigAttribute($attribute)) return null;
		
		return $this->_config[$attribute];
	}
	
	/**
	 * Set a config attribute
	 * 
	 * @param string $attribute
	 * @param unknown_type $value
	 */
	public function setConfigAttribute($attribute, $value)
	{
		$this->_config[$attribute] = $value;
	}
	
	/**
	 * Determine if a config attribute is set
	 * 
	 * @param string $attribute
	 */
	public function hasConfigAttribute($attribute)
	{
		return array_key_exists($attribute, $this->_config);
	}
	
	/**
	 * Is this document connected to a db and collection
	 */
	public function isConnected()
	{
		return (!is_null($this->getConfigAttribute('connectionGroup')) && !is_null($this->getConfigAttribute('db')) && !is_null($this->getConfigAttribute('collection')));
	}
	
	/**
	 * Is this document locked
	 * 
	 * @return boolean
	 */
	public function isLocked()
	{
		return $this->getConfigAttribute('locked');
	}
	
	/**
	 * Get the path to this document from the root document
	 * 
	 * @return string
	 */
	public function getPathToDocument()
	{
		return $this->getConfigAttribute('pathToDocument');
	}
	
	/**
	 * Set the path to this document from the root document
	 * @param unknown_type $path
	 */
	public function setPathToDocument($path)
	{
		$this->setConfigAttribute('pathToDocument', $path);
	}
	
	/**
	 * Get the full path from the root document to a property
	 * 
	 * @param $property
	 * @return string
	 */
	public function getPathToProperty($property)
	{
		if ($this->isRootDocument()) return $property;
		
		return $this->getPathToDocument().'.'.$property;
	}

	/**
	 * Is this document a root document
	 * 
	 * @return boolean
	 */
	public function isRootDocument()
	{
		return is_null($this->getPathToDocument());
	}
	
/**
	 * Determine if this document has a key
	 * 
	 * @return boolean
	 */
	public function hasKey()
	{
		return ($this->isRootDocument() && $this->isConnected());
	}
	
	/**
	 * Is this document a child element of a document set
	 * 
	 * @return boolean
	 */
	public function isParentDocumentSet()
	{
		return $this->_config['parentIsDocumentSet'];
	}
	
	/**
	 * Determine if the document has certain criteria
	 * 
	 * @return boolean
	 */
	public function hasCriteria($property)
	{
		return array_key_exists($property, $this->_config['criteria']);
	}
	
	/**
	 * Add criteria
	 * 
	 * @param string $property
	 * @param MongoId $id
	 */
	public function setCriteria($property = null, $value = null)
	{
		$this->_config['criteria'][$property] = $value;
	}
	
	/**
	 * Get criteria
	 * 
	 * @param string $property
	 * @return mixed
	 */
	public function getCriteria($property = null)
	{
		if (is_null($property)) return $this->_config['criteria'];
		
		if (!array_key_exists($property, $this->_config['criteria'])) return null;
		
		return $this->_config['criteria'][$property];
	}
	
	/**
	 * Fetch an instance of MongoDb
	 * 
	 * @param boolean $writable
	 * @return MongoDb
	 */
	public function _getMongoDb($writable = true)
	{
		if (is_null($this->getConfigAttribute('db'))) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not fetch instance of MongoDb. Document is not connected to a db.');
		}
		
		if ($writable) $connection = Shanty_Mongo::getWriteConnection($this->getConfigAttribute('connectionGroup'));
		else $connection = Shanty_Mongo::getReadConnection($this->getConfigAttribute('connectionGroup'));
		
		return $connection->selectDB($this->getConfigAttribute('db'));
	}
	
	/**
	 * Fetch an instance of MongoCollection
	 * 
	 * @param boolean $writable
	 * @return MongoCollection
	 */
	public function _getMongoCollection($writable = true)
	{
		if (is_null($this->getConfigAttribute('collection'))) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not fetch instance of MongoCollection. Document is not connected to a collection.');
		}
		
		return $this->_getMongoDb($writable)->selectCollection($this->getConfigAttribute('collection'));
	}

	/**
	 * Apply a set of requirements
	 * 
	 * @param array $requirements
	 */
	public function applyRequirements($requirements, $dirty = true)
	{
		if ($dirty) {
			$requirements = static::makeRequirementsTidy($requirements);
		}
		
		$this->_docRequirements = static::mergeRequirements($this->_docRequirements, $requirements);
	}
	
	/**
	 * Test if this document has a particular requirement
	 * 
	 * @param string $property
	 * @param string $requirement
	 */
	public function hasRequirement($property, $requirement)
	{
		if (!array_key_exists($property, $this->_docRequirements)) return false;
		
		switch($requirement) {
			case 'Document':
			case 'DocumentSet':
				foreach ($this->_docRequirements[$property] as $requirementSearch => $params) {
					$standardClass = 'Shanty_Mongo_'.$requirement;
					
					// Return basic document or document set class if requirement matches
					if ($requirementSearch == $requirement) {
						return $standardClass;
					}
					
					// Find the document class
					$matches = array();
					preg_match("/^{$requirement}:([A-Za-z][\w\-]*)$/", $requirementSearch, $matches);
					
					if (!empty($matches)) {
						if (!class_exists($matches[1])) {
							require_once 'Shanty/Mongo/Exception.php';
							throw new Shanty_Mongo_Exception("$requirement class of '{$matches[1]}' does not exist");
						}
						
						if (!is_subclass_of($matches[1], $standardClass)) {
							require_once 'Shanty/Mongo/Exception.php';
							throw new Shanty_Mongo_Exception("$requirement of '{$matches[1]}' sub is not a class of $standardClass does not exist");
						}
						
						return $matches[1];
					}
				}
				
				return false;
		}
		
		return array_key_exists($requirement, $this->_docRequirements[$property]);
	}
	
	/**
	 * Get all requirements. If prefix is provided then only the requirements for 
	 * the properties that start with prefix will be returned.
	 * 
	 * @param string $prefix
	 */
	public function getRequirements($prefix = null)
	{
		// If no prefix is provided return all requirements
		if (is_null($prefix)) return $this->_docRequirements;
		
		// Find requirements for all properties starting with prefix
		$properties = array_filter(array_keys($this->_docRequirements), function($value) use ($prefix) {
			return (substr_compare($value, $prefix, 0, strlen($prefix)) == 0 && strlen($value) > strlen($prefix));
		});
		
		$requirements = array_intersect_key($this->_docRequirements, array_flip($properties));
		
		// Remove prefix from requirement key
		$newRequirements = array();
		array_walk($requirements, function($value, $key) use ($prefix, &$newRequirements) {
			$newRequirements[substr($key, strlen($prefix))] = $value;
		});
		
		return $newRequirements;
	}
	
	/**
	 * Add a requirement to a property
	 * 
	 * @param string $property
	 * @param string $requirement
	 */
	public function addRequirement($property, $requirement, $options = null)
	{
		if (!array_key_exists($property, $this->_docRequirements)) {
			$this->_docRequirements[$property] = array();
		}
		
		$this->_docRequirements[$property][$requirement] = $options;
	}
	
	/**
	 * Remove a requirement from a property
	 * 
	 * @param string $property
	 * @param string $requirement
	 */
	public function removeRequirement($property, $requirement)
	{
		if (!array_key_exists($property, $this->_docRequirements)) return;
		
		foreach ($this->_docRequirements[$property] as $requirementItem => $options) {
			if ($requirement === $requirementItem) {
				unset($this->_docRequirements[$property][$requirementItem]);
			}
		}
	}
	
	/**
	 * Get all the properties with a particular requirement
	 * 
	 * @param array $requirement
	 */
	public function getPropertiesWithRequirement($requirement)
	{
		$properties = array();
		
		foreach ($this->_docRequirements as $property => $requirementList) {
			if (strpos($property, '.') > 0) continue;
			
			if (array_key_exists($requirement, $requirementList)) {
				$properties[] = $property;
			}
		}
		
		return $properties;
	}
	
	/**
	 * Get all validators attached to a property
	 * 
	 * @param String $property Name of property
	 * @return Zend_Validate
	 **/
	public function getValidators($property)
	{
		$validators = new Zend_Validate();
		
		// Return if no requirements are set for this property
		if (!array_key_exists($property, $this->_docRequirements)) return $validators;

		foreach ($this->_docRequirements[$property] as $requirement => $options) {
			// continue if requirement does not exist or is not a validator requirement
			$validator = Shanty_Mongo::retrieveRequirement($requirement, $options);
			if (!$validator || !($validator instanceof Zend_Validate_Interface)) continue;
			
			$validators->addValidator($validator);
		}
		
		return $validators;
	}
	
	/**
	 * Get all filters attached to a property
	 * 
	 * @param String $property
	 * @return Zend_Filter
	 */
	public function getFilters($property)
	{
		$filters = new Zend_Filter();
		
		// Return if no requirements are set for this property
		if (!array_key_exists($property, $this->_docRequirements)) return $filters;
		
		foreach ($this->_docRequirements[$property] as $requirement => $options) {
			// continue if requirement does not exist or is not a filter requirement
			$filter = Shanty_Mongo::retrieveRequirement($requirement, $options);
			if (!$filter || !($filter instanceof Zend_Filter_Interface)) continue;
			
			$filters->addFilter($filter);
		}
		
		return $filters;
	}
	
	
	/**
	 * Test if a value is valid against a property
	 * 
	 * @param String $property
	 * @param Boolean $value
	 */
	public function isValid($property, $value)
	{
		$validators = $this->getValidators($property);
		
		return $validators->isValid($value);
	}
	
	/**
	 * Get a property
	 * 
	 * @param mixed $property
	 */
	public function getProperty($property)
	{
		// If property exists and initialised then return it
		if (array_key_exists($property, $this->_data)) {
			return $this->_data[$property];
		}

		// Fetch clean data for this property
		if (array_key_exists($property, $this->_cleanData)) {
			$data = $this->_cleanData[$property];
		}
		else {
			$data = array();
		}

		// If data is not an array then we can do nothing else with it
		if (!is_array($data)) {
			$this->_data[$property] = $data;
			return $this->_data[$property];
		}
	
		// If property is supposed to be an array then initialise an array
		if ($this->hasRequirement($property, 'Array')) {
			return $this->_data[$property] = $data;
		}
		
		// If property is a reference to another document then fetch the reference document
		$db = $this->getConfigAttribute('db');
		if (MongoDBRef::isRef($data)) {
			$collection = $data['$ref'];
			$data = MongoDBRef::get($this->_getMongoDB(false), $data);
			
			// If this is a broken reference then no point keeping it for later
			if (!$data) {
				$this->_data[$property] = null;
				return $this->_data[$property];
			}
			
			$reference = true;
		}
		else {
			$collection = $this->getConfigAttribute('collection');
			$reference = false;
		}
		
		// Find out the class name of the document or document set we are loaded
		if ($className = $this->hasRequirement($property, 'DocumentSet')) {
			$docType = 'Shanty_Mongo_DocumentSet';
		}
		else {
			$className = $this->hasRequirement($property, 'Document');
			
			// Load a document anyway so long as $data is not empty
			if (!$className && !empty($data)) {
				$className = 'Shanty_Mongo_Document';
			}
			
			if ($className) $docType = 'Shanty_Mongo_Document';
		}
		
		// Nothing else to do
		if (!$className) return null;
		
		// Configure property for document/documentSet usage
		$config = array();
		$config['new'] = empty($data);
		$config['connectionGroup'] = $this->getConfigAttribute('connectionGroup');
		$config['db'] = $this->getConfigAttribute('db');
		$config['collection'] = $collection;
		$config['requirementModifiers'] = $this->getRequirements($property.'.');
		$config['hasId'] = $this->hasRequirement($property, 'hasId');
		
		if (!$reference) {
			$config['pathToDocument'] = $this->getPathToProperty($property);
			$config['criteria'] = $this->getCriteria();
		}
		
		// Initialise document
		$document = new $className($data, $config);
		
		// if this document was a reference then remember that
		if ($reference) {
			$this->_references->attach($document);
		}
		
		$this->_data[$property] = $document;
		return $this->_data[$property];
	}
	
	/**
	 * Set a property
	 * 
	 * @param mixed $property
	 * @param mixed $value
	 */
	public function setProperty($property, $value)
	{
		if (substr($property, 0, 1) == '_') {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception("Can not set private property '$property'");
		}
		
		$validators = $this->getValidators($property);
		
		// Throw exception if value is not valid
		if (!is_null($value) && !$validators->isValid($value)) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception(implode($validators->getMessages(), "\n"));
		}
		
		// Unset property
		if (is_null($value)) {
			$this->_data[$property] = null;
			return;
		}
		
		if ($value instanceof Shanty_Mongo_Document && !$this->hasRequirement($property, 'AsReference')) {
			if (!$value->isNewDocument() || !$value->isRootDocument()) {
				$documentClass = get_class($value);
				$value = new $documentClass($value->export(), array('new' => false, 'pathToDocument' => $this->getPathToProperty($property)));
			}
			else {
				$value->setPathToDocument($this->getPathToProperty($property));
			}
			
			$value->setConfigAttribute('connectionGroup', $this->getConfigAttribute('connectionGroup'));
			$value->setConfigAttribute('db', $this->getConfigAttribute('db'));
			$value->setConfigAttribute('collection', $this->getConfigAttribute('collection'));
			$value->setConfigAttribute('criteria', $this->getCriteria());
			$value->applyRequirements($this->getRequirements($property.'.'));
		}
		
		// Filter value
		$value = $this->getFilters($property)->filter($value);
		
		$this->_data[$property] = $value;
	}
	
	/**
	 * Determine if this document has a property
	 * 
	 * @param $property
	 * @return boolean
	 */
	public function hasProperty($property)
	{
		// If property has been initialised
		if (array_key_exists($property, $this->_data)) {
			return !is_null($this->_data[$property]);
		}
		
		// If property has not been initialised
		if (array_key_exists($property, $this->_cleanData)) {
			return !is_null($this->_cleanData[$property]);
		}
		
		return false;
	}

	/**
	 * Get a list of all property keys in this document
	 */
	public function getPropertyKeys()
	{
		$keyList = array();
		$doNoCount = array();
		
		foreach ($this->_data as $property => $value) {
			if (($value instanceof Shanty_Mongo_Document && !$value->isEmpty()) || 
				(!($value instanceof Shanty_Mongo_Document) && !is_null($value))) {
				$keyList[] = $property;
			}
			else {
				$doNoCount[] = $property;
			}
		}
		
		foreach ($this->_cleanData as $property => $value) {
			if (in_array($property, $keyList, true) || in_array($property, $doNoCount, true)) continue;
			
			if (!is_null($value)) $keyList[] = $property;
		}
		
		return $keyList;
	}
	
	/**
	 * Create a reference to this document
	 * 
	 * @return array
	 */
	public function createReference()
	{
		if (!$this->isRootDocument()) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not create reference. Document is not a root document');
		}
		
		if (!$this->isConnected()) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not create reference. Document does not connected to a db and collection');
		}
		
		return MongoDBRef::create($this->getConfigAttribute('collection'), $this->getId());
	}
	
	/**
	 * Test to see if a document is a reference in this document
	 * 
	 * @param Shanty_Mongo_Document $document
	 * @return boolean
	 */
	public function isReference(Shanty_Mongo_Document $document)
	{
		return $this->_references->contains($document);
	}
	
	/**
	 * Export all data
	 * 
	 * @return array
	 */
	public function export()
	{
		$exportData = $this->_cleanData;
		
		foreach ($this->_data as $property => $value) {
			// If property has been deleted
			if (is_null($value)) {
				unset($exportData[$property]);
				continue;
			}
			
			// If property is a document
			if ($value instanceof Shanty_Mongo_Document) {
				// Make when exporting from a documentset look up the correct requirement index
				if ($this instanceof Shanty_Mongo_DocumentSet) {
					$requirementIndex = Shanty_Mongo_DocumentSet::DYNAMIC_INDEX;
				}
				else {
					$requirementIndex = $property;
				}
				
				// If document is supposed to be a reference
				if ($this->hasRequirement($requirementIndex, 'AsReference') || $this->isReference($value)) {
					$exportData[$property] = $value->createReference();
					continue;
				}
				
				$data = $value->export();
				if (!empty($data)) {
					$exportData[$property] = $data;
				}
				continue;
			}
			
			$exportData[$property] = $value;
		}
		
		// make sure required properties are not empty
		$requiredProperties = $this->getPropertiesWithRequirement('Required');
		foreach ($requiredProperties as $property) {
			if (!isset($exportData[$property]) || (is_array($exportData[$property]) && empty($exportData[$property]))) {
				require_once 'Shanty/Mongo/Exception.php';
				throw new Shanty_Mongo_Exception("Property '{$property}' must not be null.");
			}
		}
		
		return $exportData;
	}
	
	/**
	 * Is this document a new document
	 * 
	 * @return boolean
	 */
	public function isNewDocument()
	{
		return ($this->_config['new']);
	}
	
	/**
	 * Test to see if this document is empty
	 * 
	 * @return Boolean
	 */
	public function isEmpty()
	{
		$doNoCount = array();
		
		foreach ($this->_data as $property => $value) {
			if ($value instanceof Shanty_Mongo_Document) {
				if (!$value->isEmpty()) return false;
			}
			elseif (!is_null($value)) {
				return false;
			}
			
			$doNoCount[] = $property;
		}
		
		foreach ($this->_cleanData as $property => $value) {
			if (in_array($property, $doNoCount)) {
				continue;
			}
			
			if (!is_null($value)) {
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * Convert data changes into operations
	 * 
	 * @param array $data
	 */
	public function processChanges(array $data = array())
	{
		foreach ($data as $property => $value) {
			if ($property === '_id') continue;
			
			if (!array_key_exists($property, $this->_cleanData)) {
				$this->addOperation('$set', $property, $value);
				continue;
			}
			
			$newValue = $value;
			$oldValue = $this->_cleanData[$property];
			
			if (MongoDBRef::isRef($newValue) && MongoDBRef::isRef($oldValue)) {
				$newValue['$id'] = $newValue['$id']->__toString();
				$oldValue['$id'] = $oldValue['$id']->__toString();
			}
			
			if ($newValue !== $oldValue) {
				$this->addOperation('$set', $property, $value);
			}
		}
		
		foreach ($this->_cleanData as $property => $value) {
			if (array_key_exists($property, $data)) continue;
			
			$this->addOperation('$unset', $property, 1);
		}
	}
	
	/**
	 * Save this document
	 * 
	 * @param boolean $entierDocument Force the saving of the entier document, instead of just the changes
	 * @param boolean $safe If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the update did not succeed
	 * @return boolean Result of save
	 */
	public function save($entierDocument = false, $safe = true)
	{
		if (!$this->isConnected()) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not save documet. Document is not connected to a db and collection');
		}
		
		if ($this->isLocked()) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not save documet. Document is locked.');
		}
		
		## execute pre hooks
		if ($this->isNewDocument()) $this->preInsert();
		else $this->preUpdate();
		
		$this->preSave();
		
		$exportData = $this->export();
		
		if ($this->isRootDocument() && ($this->isNewDocument() || $entierDocument)) {
			// Save the entier document
			$operations = $exportData;
		}
		else {
			// Update an existing document and only send the changes
			if (!$this->isRootDocument()) {
				// are we updating a child of an array?
				if ($this->isNewDocument() && $this->isParentDocumentSet()) {
					$this->_operations['$push'][$this->getPathToDocument()] = $exportData;
					$exportData = array();
					
					/**
					 * We need to lock this document because it has an incomplete document path and there is no way to find out it's true path.
					 * Locking prevents overriding the parent array on another save() after this save().
					 */
					$this->setConfigAttribute('locked', true);
				}
			}
			
			// Convert all data changes into sets and unsets
			$this->processChanges($exportData);
			
			$operations = $this->getOperations(true);

			// There are no changes, return so we don't blank the object
			if (empty($operations)) {
				return true;
			}
		}
		
		$result = $this->_getMongoCollection(true)->update($this->getCriteria(), $operations, array('upsert' => true, 'safe' => $safe));
		$this->_data = array();
		$this->_cleanData = $exportData;
		$this->purgeOperations(true);
		
		// Run post hooks
		if ($this->isNewDocument()) $this->postInsert();
		else $this->postUpdate();
		
		$this->postSave();
		
		// This is not a new document anymore
		$this->setConfigAttribute('new', false);
		
		return $result;
	}
	
	/**
	 * Save this document without waiting for a response from the server
	 * 
	 * @param boolean $entierDocument Force the saving of the entier document, instead of just the changes
	 * @return boolean Result of save
	 */
	public function saveUnsafe($entierDocument = false)
	{
		return $this->save($entierDocument, false);
	}
	
	/**
	 * Delete this document
	 * 
	 * $return boolean Result of delete
	 */
	public function delete($safe = true)
	{
		if (!$this->isConnected()) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not delete document. Document is not connected to a db and collection');
		}
	
		if ($this->isLocked()) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception('Can not save documet. Document is locked.');
		}
		
		$mongoCollection = $this->_getMongoCollection(true);
		
		// Execute pre delete hook
		$this->preDelete();
		
		if (!$this->isRootDocument()) {
			$result = $mongoCollection->update($this->getCriteria(), array('$unset' => array($this->getPathToDocument() => 1)), array('safe' => $safe));
		}
		else {
			$result = $mongoCollection->remove($this->getCriteria(), array('justOne' => true, 'safe' => $safe));
		}
		
		// Execute post delete hook
		$this->postDelete();
		
		return $result;
	}
	
	/**
	 * Get a property
	 * 
	 * @param $property
	 * @return mixed
	 */
	public function __get($property)
	{
		return $this->getProperty($property);
	}
	
	/**
	 * Set a property
	 * 
	 * @param string $property
	 * @param mixed $value
	 */
	public function __set($property, $value)
	{
		return $this->setProperty($property, $value);
	}
	
	/**
	 * Test to see if a property is set
	 * 
	 * @param string $property
	 */
	public function __isset($property)
	{
		return $this->hasProperty($property);
	}
	
	/**
	 * Unset a property
	 * 
	 * @param string $property
	 */
	public function __unset($property)
	{
		$this->_data[$property] = null;
	}
	
	/**
	 * Get an offset
	 * 
	 * @param string $offset
	 * @return mixed
	 */
	public function offsetGet($offset)
	{
		return $this->getProperty($offset);
	}
	
	/**
	 * set an offset
	 * 
	 * @param string $offset
	 * @param mixed $value
	 */
	public function offsetSet($offset, $value)
	{
		return $this->setProperty($offset, $value);
	}
	
	/**
	 * Test to see if an offset exists
	 * 
	 * @param string $offset
	 */
	public function offsetExists($offset)
	{
		return $this->hasProperty($offset);
	}
	
	/**
	 * Unset a property
	 * 
	 * @param string $offset
	 */
	public function offsetUnset($offset)
	{
		$this->_data[$offset] = null;
	}
	
	/**
	 * Count all properties in this document
	 * 
	 * @return int
	 */
	public function count()
	{
		return count($this->getPropertyKeys());
	}
	
	/**
	 * Get the document iterator
	 * 
	 * @return Shanty_Mongo_DocumentIterator
	 */
	public function getIterator()
	{
		return new Shanty_Mongo_Iterator_Default($this);
	}
	
	/**
	 * Get all operations
	 * 
	 * @param Boolean $includingChildren Get operations from children as well
	 */
	public function getOperations($includingChildren = false)
	{
		$operations = $this->_operations;
		if ($includingChildren) {
			foreach ($this->_data as $property => $document) {
				if (!($document instanceof Shanty_Mongo_Document)) continue;
				
				if (!$this->isReference($document) && !$this->hasRequirement($property, 'AsReference')) {
					$operations = array_merge_recursive($operations, $document->getOperations(true));
				}
			}
		}
		
		return $operations;
	}
	
	/**
	 * Remove all operations
	 * 
	 * @param Boolean $includingChildren Remove operations from children as wells
	 */
	public function purgeOperations($includingChildren = false)
	{
		if ($includingChildren) {
			foreach ($this->_data as $property => $document) {
				if (!($document instanceof Shanty_Mongo_Document)) continue;
				
				if (!$this->isReference($document) || $this->hasRequirement($property, 'AsReference')) {
					$document->purgeOperations(true);
				}
			}
		}
		
		$this->_operations = array();
	}
	
	/**
	 * Add an operation
	 * 
	 * @param string $operation
	 * @param array $data
	 */
	public function addOperation($operation, $property = null, $value = null)
	{
		// Make sure the operation is valid
		if (!Shanty_Mongo::isValidOperation($operation)) {
			require_once 'Shanty/Mongo/Exception.php';
			throw new Shanty_Mongo_Exception("'{$operation}' is not valid operation");
		}
		
		// Prime the specific operation
		if (!array_key_exists($operation, $this->_operations)) {
			$this->_operations[$operation] = array();
		}
		
		// Save the operation
		if (is_null($property)) {
			$path = $this->getPathToDocument();
		}
		else {
			$path = $this->getPathToProperty($property);
		}
		
		// Mix operation with existing operations if needed
		switch($operation) {
			case '$pushAll':
			case '$pullAll':
				if (!array_key_exists($path, $this->_operations[$operation])) {
					break;
				}
				
				$value = array_merge($this->_operations[$operation][$path], $value);
				break;
		}
		
		$this->_operations[$operation][$path] = $value;
	}
	
	/**
	 * Increment a property by a specified amount
	 * 
	 * @param string $property
	 * @param int $value
	 */
	public function inc($property, $value = 1)
	{
		return $this->addOperation('$inc', $property, $value);
	}
	
	/**
	 * Push a value to a property
	 * 
	 * @param string $property
	 * @param mixed $value
	 */
	public function push($property = null, $value = null)
	{
		// Export value if needed
		if ($value instanceof Shanty_Mongo_Document) {
			$value = $value->export();
		}
		
		return $this->addOperation('$pushAll', $property, array($value));
	}
	
	/**
	 * Pull all occurrences a value from an array
	 * 
	 * @param string $property
	 * @param mixed $value
	 */
	public function pull($property, $value)
	{
		return $this->addOperation('$pullAll', $property, $value);
	}
	
	/*
	 * Adds value to the array only if its not in the array already.
	 * 
	 * @param string $property
	 * @param mixed $value
	 */
	public function addToSet($property, $value)
	{
		return $this->addOperation('$addToSet', $property, $value);
	}
	
	/*
	 * Removes an element from an array
	 * 
	 * @param string $property
	 * @param mixed $value
	 */
	public function pop($property, $value)
	{
		return $this->addOperation('$pop', $property, $value);
	}
}
Back to Top