-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathActiveRecord.php
More file actions
2633 lines (2252 loc) · 63.9 KB
/
ActiveRecord.php
File metadata and controls
2633 lines (2252 loc) · 63.9 KB
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
set_include_path(get_include_path().PATH_SEPARATOR.dirname(__FILE__) . DIRECTORY_SEPARATOR);
set_include_path(get_include_path() . PATH_SEPARATOR.dirname(__FILE__) . DIRECTORY_SEPARATOR . "schema" . DIRECTORY_SEPARATOR);
set_include_path(get_include_path() . PATH_SEPARATOR.dirname(__FILE__) . DIRECTORY_SEPARATOR . "query" . DIRECTORY_SEPARATOR);
set_include_path(get_include_path() . PATH_SEPARATOR.dirname(__FILE__) . DIRECTORY_SEPARATOR . "query" . DIRECTORY_SEPARATOR . "filter" . DIRECTORY_SEPARATOR);
set_include_path(get_include_path() . PATH_SEPARATOR.dirname(__FILE__) . DIRECTORY_SEPARATOR . "schema" . DIRECTORY_SEPARATOR . "datatype" . DIRECTORY_SEPARATOR);
if (!function_exists('array_fill_keys'))
{
function array_fill_keys($array, $values)
{
if (is_array($array))
{
foreach($array as $key => $value)
{
$arraydisplay[$array[$key]] = $values;
}
}
return $arraydisplay;
}
}
$dir = dirname(__file__) . '/';
include_once($dir . 'ARSet.php');
include_once($dir . 'ARValueMapper.php');
include_once($dir . 'schema/ARSchema.php');
include_once($dir . 'query/filter/ARFieldHandle.php');
include_once($dir . 'query/filter/ARExpressionHandle.php');
include_once($dir . 'query/filter/ARSelectFilter.php');
include_once($dir . 'query/filter/Condition.php');
include_once($dir . 'query/ARSelectQueryBuilder.php');
include_once($dir . 'ARShortHand.php');
/**
*
* Database record base class
*
* You must implement self::defineSchema() in every new subclass
*
* <code>
* MyModel extends ActiveRecord
* {
* public static function defineSchema($className = __CLASS__) {
* // loading schema object to work with
* $schema = self::getSchemaInstance($className);
* $schema->setName("MyTable");
* $schema->registerField(new ARField("myFieldName"));
*
* // ...
* }
* }
* </code>
*
* @see ARField
* @see ARPrimaryKeyField
* @see ARForeignKeyField
*
* @package activerecord
* @author Integry Systems
*
*/
abstract class ActiveRecord implements Serializable
{
/**
* Database connection object
*
* @var PDO
*/
private static $dbConnection = null;
/**
* DSN string for a database connection (Database Source Name)
* (for using in static context)
*
* @var string
*/
private static $dsn = "";
/**
* Schema mapper
*
* @var ARSchemaMap
*/
protected static $schemaMap = null;
public static $recordPool = null;
/**
* Indicates if the record is deleted from database
*
* @var boolean
*/
private $isDeleted = false;
/**
* Database connection instance (refererences to self::$dbConnection)
*
* @see self::$dbConnection
* @var PDO
*/
private $db = null;
/**
* Schema of this instance (defines a record structure)
*
* @var ARSchema
*/
private $schema = null;
/**
* Record data
*
* @var ARValueMapper[]
*/
protected $data = array();
/**
* A helper const which should be used as a "magick number" to load referenced records
*
* @see self::getRecordSet()
*
*/
const LOAD_REFERENCES = true;
/**
* A helper const to use as a "magick number" to indicate that record data shoul be loaded from a database immediately
* @see self::getInstanceByID()
*
*/
const LOAD_DATA = true;
const PERFORM_INSERT = 1;
const PERFORM_UPDATE = 2;
const RECURSIVE = true;
const NON_RECURSIVE = false;
const TRANSFORM_ARRAY = true;
/**
* Is record data loaded from a database?
*
* @var bool
*/
protected $isLoaded = false;
/**
* For emulating nested transactions
*
* @var bool
*/
public static $transactionLevel = 0;
public static $logger = null;
/**
* Cached object array data from the current toArray call stack
*/
protected static $toArrayData = array();
protected $customSerializeData = array();
protected $cachedId = null;
private $isDestructing = false;
/**
* ActiveRecord constructor. Never use it directly
*
* @see self::getNewInstance()
* @see self::getInstanceByID()
*/
protected function __construct($data = array(), $recordID = null)
{
$this->schema = self::getSchemaInstance(get_class($this));
$this->createDataAccessVariables($data, $recordID);
}
/**
* Creates data containers and instance variables to directly access ValueContainers
* (record field data)
*
* Record fields type of PKField has no direct access (instance variables are not created)
*
*/
private function createDataAccessVariables($data = array(), $recordID = null)
{
foreach($this->schema->getFieldList() as $name => $field)
{
$this->data[$name] = new ARValueMapper($field, isset($data[$name]) ? $data[$name] : null);
if (!($field instanceof ARPrimaryKey))
{
$this->$name = $this->data[$name];
}
}
if ($recordID)
{
$this->setID($recordID, false);
$this->storeToPool();
}
if ($data)
{
$this->isLoaded = true;
}
$this->createReferencedRecords($data, true);
}
private function createReferencedRecords($data, $initialState = true)
{
foreach ($this->schema->getForeignKeyList() as $name => $field)
{
$referenceName = $field->getReferenceName();
$foreignClassName = $field->getForeignClassName();
if ((!($this->data[$name]->get() instanceof ActiveRecord) || !$this->data[$name]->get()->isLoaded()) && isset($data[$name]))
{
if (!isset($data[$referenceName]))
{
foreach (array($referenceName, array_pop(explode('_', $referenceName))) as $referenceName)
{
if (isset($data[$referenceName]))
{
break;
}
}
}
if (isset($data[$referenceName]))
{
/*
foreach($data as $referecedTableName => $referencedData)
{
if (($referenceName != $referecedTableName) && $referencedData && !isset($data[$referenceName][$referecedTableName]))
{
$data[$referenceName][$referecedTableName] = $referencedData;
}
}
*/
if (!self::extractRecordID(self::getSchemaInstance($foreignClassName), $data[$referenceName]))
{
$data[$referenceName] = null;
}
$this->data[$name]->set(self::getInstanceByID($foreignClassName, $data[$name], false, null, $data[$referenceName]), false);
}
else
{
$this->data[$name]->set(self::getInstanceByID($foreignClassName, $data[$name], false, null), false);
}
}
if ($initialState)
{
// Making first letter lowercase
$referenceName = $field->getReferenceFieldName();
$referenceName = strtolower(substr($referenceName, 0, 1)).substr($referenceName, 1);
$this->$referenceName = $this->data[$name];
}
}
}
/**
* Creates or gets an already created Schema object for a given class $className
*
* @param string $className
*
* @return ARSchema
*/
public static function getSchemaInstance($className)
{
static $cache;
if (!isset(self::$schemaMap[$className]))
{
/********
+++ UGLY UGLY UGLY +++ :(
@todo: add generic schema caching interface
*********/
/*
if (!$cache)
{
$cache = ClassLoader::getRealPath('cache.schema.');
if (!file_exists($cache))
{
mkdir($cache, 0777);
chmod($cache, 0777);
}
}
$cacheFile = $cache . $className . '.php';
if (file_exists($cacheFile))
{
self::$schemaMap[$className] = include $cacheFile;
return self::$schemaMap[$className];
}
*/
self::$schemaMap[$className] = new ARSchema();
call_user_func(array($className, 'defineSchema'));
if (!self::$schemaMap[$className]->isValid())
{
throw new ARException("Invalid schema (".$className.") definition! Make sure it has a name assigned and fields defined (record structure)");
}
/*file_put_contents($cacheFile, '<?php return unserialize(' . var_export(serialize(self::$schemaMap[$className]), true) . '); ?>');*/
//chmod($cacheFile, 0777);
}
return self::$schemaMap[$className];
}
/**
* Prepares a database connection for use.
*
* This method involves some kind of optimisation: database connection library
* source is loaded and connection instance is created only when it is really needed
*
*/
private function setupDBConnection()
{
$this->db = self::getDBConnection();
}
/**
* Return a database connection object
*
* @return PDO db object
*/
public static function getDBConnection()
{
if (!self::$dbConnection)
{
self::getLogger()->logQuery("Creating a database connection");
$dsn = parse_url(self::$dsn);
$params = array();
if ('mysql' == $dsn['scheme'])
{
$params = array(
PDO::MYSQL_ATTR_FOUND_ROWS => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\';' //@@session.sql_mode='';
);
}
try
{
self::$dbConnection = new PDO($dsn['scheme'] . ':dbname=' . substr($dsn['path'], 1) . ';host=' . $dsn['host'], $dsn['user'], !empty($dsn['password']) ? $dsn['password'] : '', $params);
self::$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
throw new SQLException($e->getMessage());
}
self::getLogger()->logQueryExecutionTime();
}
return self::$dbConnection;
}
public static function resetDBConnection()
{
self::$dbConnection = null;
}
public function resetID()
{
$PKList = $this->schema->getPrimaryKeyList();
foreach ($PKList as $fieldName => $field)
{
if (!($field instanceof ARForeignKey))
{
$this->data[$fieldName]->setNull();
}
}
}
/**
* Sets a primary key value for a record
*
* @param mixed $recordID PK value, or array if PK consists of multiple fields (form: array(fieldName => value, fieldName2 -> value2, ...))
*/
public function setID($recordID, $markAsModified = true)
{
$PKList = $this->schema->getPrimaryKeyList();
if (!is_array($recordID))
{
if (count($PKList) == 1)
{
$PKFieldName = key($PKList);
//if ($this->data[$PKFieldName]->get() instanceof ARForeignKey)
if ($PKList[$PKFieldName] instanceof ARForeignKey)
{
$instance = self::getInstanceByID($this->schema->getField($PKFieldName)->getForeignClassName(), $recordID);
$this->data[$PKFieldName]->set($instance, $markAsModified);
}
else
{
$this->data[$PKFieldName]->set($recordID, $markAsModified);
}
}
else
{
throw new ARException("Primary key consists of more than one field (recordID parameter must be an associative array)");
}
}
else
{
if (count($recordID) == count($PKList))
{
foreach($recordID as $name => $value)
{
if ($this->schema->fieldExists($name))
{
$instance = self::getInstanceByID($this->schema->getField($name)->getForeignClassName(), $value);
$this->data[$name]->set($instance, $markAsModified);
}
else
{
throw new ARException("No such primary key field: ".$name." (schema: ".$this->schema->getName().")");
}
}
}
else
{
print_r($recordID);
throw new ARException("Unknown situation (not implemented?)");
}
}
$this->cachedId = null;
}
/**
* Returns a primary key value of record
*
* @param mixed $recordID
* @return mixed record id. If primary key consists of more than one field an array is returned
*/
public function getID()
{
if (!$this->cachedId)
{
$PKList = $this->schema->getPrimaryKeyList();
$PK = array();
foreach($PKList as $name => $field)
{
if ($field instanceof ARPrimaryForeignKeyField)
{
if (!$this->data[$name]->get())
{
return false;
}
$PK[$name] = $this->data[$name]->get()->getID();
}
else
{
if (!empty($this->data[$name]))
{
$PK[$name] = $this->data[$name]->get();
}
}
}
if (count($PK) == 1)
{
$this->cachedId = array_shift($PK);
}
else
{
$this->cachedId = $PK;
}
}
return $this->cachedId;
}
/**
* Creates a new instance of record
*
* Use this method when you are going to create a new persistent object. If you
* need to load an existing one call self::getInstanceByID()
*
* @see self::getInstanceByID()
* @param string $className
* @param array $data Field values (associative array)
* @return ActiveRecord
*/
public static function getNewInstance($className, $data = array(), $recordID = null)
{
return new $className($data, $recordID);
}
/**
* Sets a DSN (database connection configuration info)
*
* @param string $dsn
*/
public static function setDSN($dsn)
{
self::$dsn = $dsn;
}
/**
* Gets an existing record instance (persisted on a database).
*
* Object representing concrete record gets created only once (Flyweight pattern)
*
* @param string $className Class representing record
* @param mixed $recordID
* @param bool $loadRecordData
* @param bool $loadReferencedRecords
* @param array $data Record data array (may include referenced record data)
*
* @link http://en.wikipedia.org/wiki/Flyweight_pattern
*
* @return ActiveRecord
*/
public static function getInstanceByID($className, $recordID, $loadRecordData = false, $loadReferencedRecords = false, $data = array())
{
if (is_numeric($className) && (get_called_class() != __CLASS__) && (get_called_class() != 'ActiveRecordModel'))
{
$data = $loadReferencedRecords;
$loadReferencedRecords = $loadRecordData;
$loadRecordData = $recordID;
$recordID = $className;
$className = get_called_class();
}
$instance = call_user_func_array(array($className, 'retrieveFromPool'), array($className, $recordID));
if ($instance == null || !is_object($instance))
{
$instance = self::getNewInstance($className, $data, $recordID);
$instance->setID($recordID, false);
$instance->storeToPool();
}
else if (!$instance->isLoaded() && !empty($data))
{
$instance->createDataAccessVariables($data, $recordID);
}
if ($loadRecordData)
{
$instance->load($loadReferencedRecords);
}
return $instance;
}
/**
* Returns an existing record instance if it exists - otherwise a new instance will be returned
*
* @param string $className Class representing record
* @param mixed $recordID
*
* @return ActiveRecord
*/
public static function getInstanceByIdIfExists($className, $recordID, $returnNewIfNotExist = true)
{
if (self::objectExists($className, $recordID))
{
$instance = self::getInstanceByID($className, $recordID, self::LOAD_DATA);
}
else if ($returnNewIfNotExist)
{
$instance = self::getNewInstance($className);
$instance->setID($recordID);
}
else
{
return null;
}
return $instance;
}
/**
* Removes a ActiveRecord subclass instance from a record pool (needed for unit testing only)
*
* @param ActiveRecord $instance
*/
public static function removeFromPool(ActiveRecord $instance)
{
$hash = self::getRecordHash($instance->getID());
$className = get_class($instance);
$instance->markAsNotLoaded();
self::$recordPool[$className][$hash] = null;
}
/**
* This method should only be used for unit testing in tearDown method
*
*/
public static function removeClassFromPool($className)
{
unset(self::$recordPool[$className]);
}
/**
* This method should only be used for unit testing
*
*/
public static function clearPool()
{
self::$recordPool = null;
self::$recordPool = array();
self::$toArrayData = null;
self::$toArrayData = array();
}
/**
* Stores ActiveRecord subclass instance in a record pool
*
* @param ActiveRecord $instance
*/
protected function storeToPool()
{
self::$recordPool[get_class($this)][self::getRecordHash($this->getID())] = $this;
}
/**
* Retrieves ActiveRecord subclass instance from a record pool
*
* @param string $className
* @param mixed $recordID
* @return ActiveRecord Instance of requested object or null if object is not stored in a pool
*/
public static function retrieveFromPool($className, $recordID = null)
{
if(!is_null($recordID))
{
if ($recordID instanceof ActiveRecord)
{
$recordID = $recordID->getID();
}
$hash = self::getRecordHash($recordID);
if ($hash && !empty(self::$recordPool[$className][$hash]))
{
if (self::$recordPool[$className][$hash] instanceof $className)
{
return self::$recordPool[$className][$hash];
}
}
return null;
}
else if (isset(self::$recordPool[$className]))
{
return self::$recordPool[$className];
}
return array();
}
/**
* Gets a unique string representing concrete record
*
* @param mixed $recordID
* @return string
*/
protected static function getRecordHash($recordID)
{
if (!is_array($recordID))
{
return $recordID;
}
else
{
ksort($recordID);
return implode("-", $recordID);
}
}
/**
* Creates a select query object for a table identified by an ActiveRecord class name
*
* @param string $className
* @param bool $loadReferencedRecords Join records on foreign keys?
* @return string
*/
public static function createSelectQuery($className, &$loadReferencedRecords = false)
{
$schema = self::getSchemaInstance($className);
$schemaName = $schema->getName();
$query = new ARSelectQueryBuilder();
$query->includeTable($schemaName);
// Add main table fields to the select query
foreach($schema->getFieldList() as $fieldName => $field)
{
$query->addField($fieldName, $schemaName);
}
$loadReferencedRecords = self::addAutoReferences($schema, $loadReferencedRecords);
if ($loadReferencedRecords)
{
self::joinReferencedTables($schema, $query, $loadReferencedRecords);
}
return $query;
}
private static function addAutoReferences(ARSchema $schema, $loadReferencedRecords)
{
if (true === $loadReferencedRecords)
{
return true;
}
// auto-referenced tables
if ($autoReferences = $schema->getRecursiveAutoReferences())
{
if (!is_array($loadReferencedRecords))
{
$loadReferencedRecords = array();
}
// clear already included references
foreach ($autoReferences as $key => $ref)
{
if (is_numeric(array_search($ref, $loadReferencedRecords)) && is_numeric($key))
{
unset($autoReferences[$key]);
}
}
return array_merge($loadReferencedRecords, $autoReferences);
}
return $loadReferencedRecords;
}
private function array_invert($arr)
{
$flipped = array();
foreach(array_keys($arr) as $key)
{
if(array_key_exists($arr[$key],$flipped))
{
$flipped[$arr[$key]] = array_merge((array)$flipped[$arr[$key]], (array)$key);
}
else
{
$flipped[$arr[$key]] = $key;
}
}
return $flipped;
}
/* @todo: document possible loadReferenceRecords values */
protected static function joinReferencedTables(ARSchema $schema, ARSelectQueryBuilder $query, &$loadReferencedRecords = false)
{
// do not use auto-references for single-table one level joins
if (!is_string($loadReferencedRecords))
{
$loadReferencedRecords = self::addAutoReferences($schema, $loadReferencedRecords);
}
$tables = is_array($loadReferencedRecords) ? self::array_invert($loadReferencedRecords) : $loadReferencedRecords;
$referenceList = $schema->getReferencedForeignKeyList();
$schemaName = $schema->getName();
foreach($referenceList as $name => $field)
{
$foreignClassName = $field->getForeignClassName();
$tableAlias = $field->getReferenceName();
$foreignSchema = self::getSchemaInstance($foreignClassName);
$foreignTableName = $foreignSchema->getName();
$aliasParts = explode('_', $tableAlias);
$aliasName = isset($aliasParts[1]) ? $aliasParts[1] : '';
$isSameSchema = $schema === $foreignSchema;
$notRequiredForInclusion = is_array($tables) && !isset($tables[$foreignClassName]);
$isAliasSpecified = is_array($tables) && isset($tables[$foreignClassName]) && !is_numeric($tables[$foreignClassName]);
if ($isAliasSpecified)
{
$classNamesDoNotMatch = $tables[$foreignClassName] != $aliasName;
$notReferencedAsArray = !is_array($tables[$foreignClassName]);
$notInReferencedArray = is_array($tables[$foreignClassName]) && !in_array($aliasName, $tables[$foreignClassName]);
}
if ($tables !== $schemaName)
{
if ($isSameSchema || $notRequiredForInclusion ||
($isAliasSpecified && $classNamesDoNotMatch && ($notReferencedAsArray || $notInReferencedArray))
|| (is_string($tables) && ($tables != $schemaName))
)
{
continue;
}
}
if (!$query->getJoinsByClassName($foreignTableName))
{
$tableAlias = $foreignTableName;
}
$joined = $query->joinTable($foreignTableName, $schemaName, $field->getForeignFieldName(), $name, $tableAlias);
if ($joined)
{
foreach($foreignSchema->getFieldList() as $foreignFieldName => $foreignField)
{
$query->addField($foreignFieldName, $tableAlias, $tableAlias."_".$foreignFieldName);
}
self::getLogger()->logQuery('Joining ' . $foreignClassName . ' on ' . $schemaName);
self::joinReferencedTables($foreignSchema, $query, $loadReferencedRecords);
}
}
}
/**
* Loads and sets persisted record data from a database
*
* @param bool $loadReferencedRecords
*/
public function load($loadReferencedRecords = false)
{
if ($this->isLoaded || !$this->isExistingRecord() || $this->isDeleted())
{
return false;
}
$query = self::createSelectQuery(get_class($this), $loadReferencedRecords);
$this->loadData($loadReferencedRecords, $query);
$this->isDeleted = false;
return true;
}
protected final function loadData($loadReferencedRecords, ARSelectQueryBuilder $query)
{
$className = get_class($this);
$PKCond = null;
foreach($this->schema->getPrimaryKeyList() as $name => $PK)
{
if ($PK instanceof ARForeignKey)
{
$PKValue = $this->data[$name]->get()->getID();
}
else
{
$PKValue = $this->data[$name]->get();
}
if ($PKCond == null)
{
$PKCond = new EqualsCond(new ARFieldHandle($className, $name), $PKValue);
}
else
{
$PKCond->addAND(new EqualsCond(new ARFieldHandle($className, $name), $PKValue));
}
}
$query->getFilter()->mergeCondition($PKCond);
$rowDataArray = self::fetchDataFromDB($query);
if (empty($rowDataArray))
{
throw new ARNotFoundException($className, $this->getID());
}
if (count($rowDataArray) > 1)
{
throw new ARException("Unexpected behavior: got more than one record from a database while loading single instance data");
}
$parsedRowData = self::prepareDataArray($className, $this->schema, $rowDataArray[0], $loadReferencedRecords);
$this->createDataAccessVariables($parsedRowData['recordData'], $this->getID());
if (!empty($parsedRowData['miscData']))
{
$this->miscRecordDataHandler($parsedRowData['miscData']);
}
}
/**
* Extracts a primary key value (record ID) from a data array
*
* @param string $className
* @param array $dataArray
* @return mixed
*/
protected static function extractRecordID(ARSchema $schema, $dataArray)
{
$PKList = $schema->getPrimaryKeyList();
if (count($PKList) == 1)
{
return $dataArray[key($PKList)];
}
else
{
$recordID = array();
foreach($PKList as $name => $field)
{
$recordID[$name] = $dataArray[$name];
}
return $recordID;
}
}
private function getUsedSchemas($schema, $referencedSchemaList)
{
$loadReferencedRecords = $referencedSchemaList;
$schemas = is_string($referencedSchemaList) ? $schema->getDirectlyReferencedSchemas() : $schema->getReferencedSchemas();
// remove schemas that were not loaded with this query
if (is_array($loadReferencedRecords))
{
$loadReferencedRecords = self::array_invert($loadReferencedRecords);
$filteredSchemas = array();
foreach($loadReferencedRecords as $tableName => $tableAlias)
{
if (is_numeric($tableAlias))
{
if (!isset($schemas[$tableName]))
{
if (isset($schemas[$tableName . '_' . $tableName]))
{
$tableName .= '_' . $tableName;
}
else
{
$break = false;
foreach ($schemas as $name => $collection)
{
foreach ($collection as $schema)
{
if ($schema->getName() == $tableName)
{
$tableName = $name;
$break = true;
break;
}
}
if ($break)
{
break;
}
}
}
}
$filteredSchemas[$tableName] = $schemas[$tableName][0];
}
else
{
$originalAlias = $tableAlias;
$aliases = !is_array($tableAlias) ? array($tableName . '_' . $tableAlias) : $tableAlias;
foreach ($aliases as $aliasIndex => $tableAlias)
{
// If the same table is referenced for two or more times an alias that consists of foreign key
// and referenced table name is used. However the first instance is always referenced using the
// table name only to avoid having to specify the full aliases in all WHERE conditions
if (!isset($schemas[$tableAlias]))
{
if (0 == $aliasIndex)
{
$tableAlias = $tableName;
}
else
{
$tableAlias = $tableName . '_' . $tableAlias;
}
}
if (!isset($schemas[$tableAlias]))
{
$tableAlias = $originalAlias;
}