-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelBase.php
More file actions
executable file
·1713 lines (1407 loc) · 76 KB
/
ModelBase.php
File metadata and controls
executable file
·1713 lines (1407 loc) · 76 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
namespace TestPlugin\Models {
use TestPlugin\DBResult;
use TestPlugin\PDOHelper;
use TestPlugin\SQLLoader;
use TestPlugin\Models\Referencable;
use TestPlugin\Models\Translatable;
use TestPlugin\Models\ModelCache;
use TestPlugin\FieldCondition;
use TestPlugin\UtilityFunctions;
/**
* Class ModelBase
* A class that is used to save/load/manipulate data in a database, based on subclassing and calling these functions from the subclass.
* This class operates basically like a rudimentary ORM
*
* @package TestPlugin\Models
*/
abstract class ModelBase implements \JsonSerializable {
//Base fields every model has
public $lastModified;
public $created;
public $lastUserModified;
public $id;
//
public $_serializeAllProperties = false;
public $_fieldsToSerialize = [];
//use this function to easily set the above array (which will be used when serializing)
public function setFieldsToSerialize(array $fields = [], bool $includeAllNonExtraFields = true, bool $includeExtraProps = true) {
if($includeAllNonExtraFields) {
$this->_fieldsToSerialize = $this->getProperties($includeExtraProps);
} else if($includeExtraProps) {
$this->_fieldsToSerialize = static::getExtraProperties();
}
$this->_fieldsToSerialize = array_merge($this->_fieldsToSerialize, $fields);
}
public function addFieldToSerialize(string $fieldName) {
if(!array_key_exists($fieldName, $this->_fieldsToSerialize)){
$this->_fieldsToSerialize[] = $fieldName;
}
}
public function removeFieldToSerialize(string $fieldName) {
if(array_key_exists($fieldName, $this->_fieldsToSerialize)){
foreach (array_keys($this->_fieldsToSerialize, $fieldName) as $key) {
unset($this->_fieldsToSerialize[$key]);
}
}
}
private static $modelClassesDir = "";
public static function getModelClassesDir():string {
if(empty(ModelBase::$modelClassesDir)) {
ModelBase::$modelClassesDir = implode(DIRECTORY_SEPARATOR, [
__DIR__,
'Classes',
'*.php'
]);
}
return ModelBase::$modelClassesDir;
}
private static $isDebug = false;
public static function enableDebug() {ModelBase::$isDebug = true;}
public static function disableDebug() {ModelBase::$isDebug = false;}
public static function isDebug():bool {return ModelBase::$isDebug;}
public function __construct() {
}
//extra properties not related to db
public static function isTranslatableStatic():bool {
$translatableName = Translatable::class;
return is_a(static::getFullStaticClassname(), $translatableName, true);
}
//extra properties not related to db
public function isTranslatable():bool {
$translatableName = Translatable::class;
return $this instanceof $translatableName;
}
//extra properties not related to db that we generally want to ignore when fetching from the db/saving, or when serializing
public static function getExtraProperties():array {
static $extra = [
"isDebug",
"tableName",
"_serializeAllProperties",
"_fieldsToSerialize",
"modelClassesDir",
//fields of interfaces that we always want to avoid using when saving, loading or serializing
"fieldsToTranslate"
];
return $extra;
}
//fields that need extra security to ensure anonymous users dont have access (or malicious admins / scripts)
public static function getSecureFields():array {
return [];
}
//used to filter out secure fields from a list, if they are secure (for use when those fields shouldn't be used in an "insecure" operation)
public static function filterSecureFields(array $fieldList = []):array {
if(ModelBase::isDebug() ){
error_log("----------------------------- filterSecureFields:" . self::getStaticClassname() . " -----------------------------");
}
$result = [];
if(!empty($fieldList)){
//get a list of all fields allowed for "non secure" loading
$result = array_diff($fieldList, self::getSecureFields() );
if(ModelBase::isDebug() ){
error_log("Fields to load - that aren't secure: " . print_r($result, true));
}
}
return $result;
}
//used to filter out extra fields from a list, because they won't be present in the database
public static function filterExtraFields(array $fieldList = []):array {
if(ModelBase::isDebug() ){
error_log("----------------------------- filterExtraFields:" . self::getStaticClassname() . " -----------------------------");
}
$result = [];
if(!empty($fieldList)){
$result = array_filter($fieldList, [static::class, 'extraPropertiesFilter'], ARRAY_FILTER_USE_BOTH);
if(ModelBase::isDebug() ){
error_log("Fields to load - that aren't extra: " . print_r($result, true));
}
}
return $result;
}
/**
* This is used to filter an array of fields, and remove any that are NOT valid properties of this model (via "::getPropertiesStatic")
*
* @param array $fields The fields to verify.
* @return array The fields that are valid
*/
public static function filterInvalidFields(array $fields):array {
if(ModelBase::isDebug() ){
error_log("----------------------------- filterInvalidFields:" . self::getStaticClassname() . " -----------------------------");
}
$result = [];
if(!empty($fields)){
$props = self::getPropertiesStatic();
if(ModelBase::isDebug()){
error_log("Fields specified, so ensure they belong to this object");
error_log('Fields provided:'.print_r($fields,true));
}
$result = array_intersect($fields, $props);
if(ModelBase::isDebug()){
error_log("Properties of this object:".print_r($props,true));
error_log("Fields that are in this objects properties:".print_r($result,true));
}
}
return $result;
}
public function addProperty($name, $value){
$this->{$name} = $value;
}
public static function getFullStaticClassname():string {
return static::class;
}
public function getFullClassname():string {
return get_class($this);
}
public static function getStaticClassname():string {
return UtilityFunctions::getClassWithoutNamespace(static::class);
}
public static function getStaticNamespace():string{
return __NAMESPACE__;
}
public function getClassname():string {
return UtilityFunctions::getClassWithoutNamespace(get_class($this) );
}
public function getTableName():string {
return static::getTableNameStatic();
}
public static function getTableNameStatic():string {
$tableName = "tableName";
if(property_exists(static::class, $tableName)) {
return static::$$tableName;
} else {
return static::getStaticClassname().'s';
}
}
//used to "hide" properties that are used for programming (and are unrelated to the db)
//an example could be a "many-to-many" model, such as keywords, where we dont care about the "intermediate model" just the keywords
public static function extraPropertiesFilter($name):bool {
$extraProperties = static::getExtraProperties();
return !in_array($name, $extraProperties);
}
//gets properties that should be considered when doing database work
public function getProperties(bool $getExtraProps = false, array $fieldsToInclude = []):array {
$props = array_keys(get_object_vars($this));
if(!$getExtraProps && empty($fieldsToInclude)){
$props = static::filterExtraFields($props);
}
if(!empty($fieldsToInclude)) {
$props = array_filter($props, function($k) use ($fieldsToInclude) {
return in_array($k, $fieldsToInclude);
}, ARRAY_FILTER_USE_KEY);
}
if(ModelBase::isDebug()){
error_log('getProperties of "' . static::class . '":' . print_r($props, true));
}
return $props;
}
//get properties of this model class, that should be considered for database work
public static function getPropertiesStatic(bool $getExtraProps = false, array $fieldsToInclude = []):array {
$props = array_keys(get_class_vars(static::class ));
if(!$getExtraProps && empty($fieldsToInclude)){
$props = static::filterExtraFields($props);
}
if(!empty($fieldsToInclude)) {
$props = array_filter($props, function($k) use ($fieldsToInclude) {
return in_array($k, $fieldsToInclude);
}, ARRAY_FILTER_USE_KEY);
}
if(ModelBase::isDebug()){
error_log('getPropertiesStatic of "' . static::class . '":' . print_r($props, true));
}
return $props;
}
/**
* @param bool $getExtraProps Whether to get "extra" properties (properties that exist in code, and are NOT to be persisted to the database)
* @param array $fieldsToInclude An array of fields to selectively include (or all if omitted)
* @return array An associative array of the properties of this model, and their respective values
*/
public function getPropertiesAndValues(bool $getExtraProps = false, array $fieldsToInclude = []):array {
$propsAndValues = get_object_vars($this);
if(!$getExtraProps && empty($fieldsToInclude)){
$propsAndValues = array_filter($propsAndValues, [static::class, 'extraPropertiesFilter'], ARRAY_FILTER_USE_KEY);
}
if(!empty($fieldsToInclude)) {
$propsAndValues = array_filter($propsAndValues, function($k) use ($fieldsToInclude) {
return in_array($k, $fieldsToInclude);
}, ARRAY_FILTER_USE_KEY);
}
if(ModelBase::isDebug()){
error_log('getPropertiesAndValues of "' . static::class . '":' . print_r($propsAndValues, true));
}
return $propsAndValues;
}
//only looks at properties related to db work
public function hasProperty(string $property):bool {
return in_array($property, $this->getProperties());
}
public function idIsInteger():bool {
return static::isInteger($this->id);
}
public static function isInteger($val = ""):bool {
if((!isset($val) && empty($val)) || !is_numeric($val)){
return false;
}
$isInt = filter_var($val, FILTER_VALIDATE_INT);
return ($isInt !== FALSE);
}
/**
* Gets base field names that exist on all models, that NEED a value when saving via "execute" of a prepared statement.
*
* @return array Base field names present on all models
*/
public static function getBaseFieldNames():array{
static $fieldsToPrepare = [
"lastUserModified"
//"lastModified" and "created" are defaulted to "now()" MySQL functions (so we don't need to provide values for them)
];
return $fieldsToPrepare;
}
/**
* Gets field names that are defaulted in SQL statements.
* Generally used to know which fields to NOT include when passing parameter arrays to "execute" of a prepared statement
*
* @return array The field names that are given defaults in SQL
*/
public static function geFieldNamesToDefault():array{
static $fieldsToPrepare = [
"lastModified",
"created"
];
return $fieldsToPrepare;
}
//used to translate many models at once, via a static reference of the class.
//An example of this is: Language::TranslateMany() to translate languages
public static function TranslateMany(string $langCode = "", PDOHelper $source = null, $recordIDsToTranslate = []):DBResult {
if(ModelBase::isDebug()){
error_log("----------------------------- TranslateMany: ".self::getStaticClassname()."-----------------------------");
}
$result = new DBResult();
if(empty($source)) {
$result->addMessage("Source PDOHelper is invalid.");
return $result;
}
if(empty($langCode)) {
$result->addMessage("The language code for this object is empty.");
return $result;
}
if(!self::isTranslatableStatic()) {
$result->addMessage("The object of type \"".self::getStaticClassname()."\" does not implement Translatable.");
return $result;
}
$pdo = $source->getPDOConnection();
$sqlLoader = $source->getSqlLoader();
$where = 'langTbl.'.SQLLoader::escapeFieldName('langCode').'=?';
if(!empty($recordIDsToTranslate)) {
$where .= ' AND transTbl.'.SQLLoader::escapeFieldName('translatedrecordid').' IN ('.implode(",", $recordIDsToTranslate).')';
}
$sqlPlaceholders = [
"{table_name}" => self::getTableNameStatic(),
"{model_name}" => self::getStaticClassname(),
"{model_fields}" => self::getStaticTranslatedFieldNames(),//object was checked above to implement the "Translatable" interface, so this method exists on this instance
"{where_clause}" => $where
];
$sql = $sqlLoader->getSingleSqlFileStatement("translate", $sqlPlaceholders);
if(ModelBase::isDebug()){
error_log("sql: ".$sql);
}
try {
$prepared = $pdo->prepare($sql);
$params = [$langCode];
if(!empty($recordIDsToTranslate)) {
$params = array_merge($params, $recordIDsToTranslate);
}
$success = $prepared->execute($params);
if($success) {
$dbResults = $prepared->fetchAll(\PDO::FETCH_ASSOC);
$translatedResults = [];
foreach ($dbResults as $dbResult) {
$translatedResult = new static();
$translatedResult->id = $dbResult["translatedrecordid"];
$translatedResult->langCode = $langCode;
$keyForCache = ModelCache::getModelKey($translatedResult, ["langCode","id"]);
//copy all fields to be translated to this object
foreach ($dbResult as $field => $value) {
$translatedResult->{$field} = $value;//could possibly add new fields, as the translation table could have new values NOT in the class or this object
}
ModelCache::putInCache($keyForCache, $result);
$translatedResults[] = $translatedResult;
}
$result->result = $translatedResults;
$result->success = true;
}
} catch(\PDOException $e){
$result->success = false;
if(ModelBase::isDebug()){
error_log("Exception when executing SQL:".$e->getMessage());
}
}
return $result;
}
//translate an instance of a model
public function Translate(string $langCode = "", PDOHelper $source = null):bool {
if(ModelBase::isDebug()){
error_log("----------------------------- Translate:{$this->getClassname()} -----------------------------");
}
$success = false;
if(empty($source) || empty($langCode) || !$this->idIsInteger() || ($this->id == 0) || !$this->isTranslatable()) {
return $success;
}
$keyForCache = ModelCache::getModelKey($this, ["langCode","id"]);
$dataFromCache = ModelCache::getFromCache($keyForCache);
if(!empty($dataFromCache)){
if(ModelBase::isDebug()){
error_log("Loaded from cache. Cached object:".print_r($dataFromCache,true));
}
static::populateFromArray($this, $dataFromCache);
return true;
}
$pdo = $source->getPDOConnection();
$sqlLoader = $source->getSqlLoader();
$sqlPlaceholders = [
"{table_name}" => $this->getTableName(),
"{model_name}" => $this->getClassname(),
"{model_fields}" => $this->getTranslatedFieldNames(),//object was checked above to implement the "Translatable" interface, so this method exists on this instance
"{where_clause}" => 'transTbl.'.SQLLoader::escapeFieldName('translatedrecordid').'=? AND langTbl.'.SQLLoader::escapeFieldName('langCode')."=?"
];
$sql = $sqlLoader->getSingleSqlFileStatement("translate", $sqlPlaceholders);
if(ModelBase::isDebug()){
error_log("sql: ".$sql);
}
try {
$prepared = $pdo->prepare($sql);
$success = $prepared->execute([$this->id, $langCode]);
if($success) {
$result = $prepared->fetch(\PDO::FETCH_ASSOC);
//copy all fields to be translated to this object
foreach ($result as $field => $value) {
$this->{$field} = $value;//could possibly add new fields, as the translation table could have new values NOT in the class or this object
}
$this->addProperty('langCode', $langCode);
ModelCache::putInCache($keyForCache, $result);
}
} catch(\PDOException $e){
$success = false;
if(ModelBase::isDebug()){
error_log("Exception when executing SQL:".$e->getMessage());
}
}
return $success;
}
//save a translated model, and uses the interface "Translatable" to know what fields to save/are able t be translated
public function SaveTranslation(PDOHelper $source, $fieldNamesToSave = [], bool $alreadyInTransaction = false, bool $defaultEmptyValues = true):DBResult {
if(ModelBase::isDebug()){
error_log("----------------------------- SaveTranslation:{$this->getClassname()} -----------------------------");
}
$result = new DBResult();
if(empty($source)) {
$result->messages[] = "Source PDOHelper is invalid.";
return $result;
}
if(empty($this->langCode)) {
$result->messages[] = "The language code for this object is empty.";
return $result;
}
if(!$this->idIsInteger() || (intval($this->id) <= 0)) {
$result->messages[] = "The ID for this object is empty.";
return $result;
}
if(!$this->isTranslatable()) {
$result->messages[] = "The object \"".$this->getClassname()."\" does not implement Translatable.";
return $result;
}
$pdo = $source->getPDOConnection();
$sqlLoader = $source->getSqlLoader();
$isUpdate = $this->idIsInteger() && (intval($this->id) > 0);
if(ModelBase::isDebug()){
error_log("SaveTranslation - isUpdate:" . $isUpdate);
}
//remove any prop names included in the parameter array that are NOT valid for the translation of this object
$translatedFields = $this->getTranslatedFieldNames();
if(!empty($fieldNamesToSave) && $isUpdate) {
$fieldNamesToSave = array_intersect($translatedFields, $fieldNamesToSave);
} else {//if insert, save all fields
$fieldNamesToSave = $translatedFields;
}
//the where clause is only used in an update
$whereClause = SQLLoader::escapeFieldName("translatedrecordid")."=? AND ".SQLLoader::escapeFieldName("destinationlanguageid")."=(SELECT `id` FROM {table_prefix}_Languages AS langTbl WHERE langTbl.`iso639_1`=?)";
$sqlPlaceholders = [
"{table_name}" => $this->getTableName(),
"{model_name}" => $this->getClassname(),
"{where_clause}" => $whereClause
];
if($isUpdate) {
$sqlPlaceholders["{translated_fields}"] = implode("=?, ",array_keys($fieldNamesToSave)).'=?';
} else {
$sqlPlaceholders["{translated_fields}"] = implode(", ",array_keys($fieldNamesToSave));
//get an array of "?" placeholders, including one for the "lastUserModified" property
$sqlPlaceholders["{placeholders}"] = '?, '.implode(", ",array_fill(0,count(array_keys($fieldNamesToSave)),"?") );
}
if(ModelBase::isDebug()) {
error_log('Placeholders: '.print_r($sqlPlaceholders,true));
}
$sql = $sqlLoader->getSingleSqlFileStatement(($isUpdate ? "update_translation" : "insert_translation"), $sqlPlaceholders);
try {
if(!$alreadyInTransaction) {
$pdo->beginTransaction();
}
if(ModelBase::isDebug()){
error_log("sql: ".$sql);
}
$prepared = $pdo->prepare($sql);
$dataValuesToSave = [$this->lastUserModified];
foreach($fieldNamesToSave as $fieldName) {//copy all of the translated field values we intend to save
$dataValuesToSave[] = $this->$fieldName;
}
if(!$isUpdate) {
array_unshift($dataValuesToSave, $this->langCode);//if this is an insert, we also have to provide the language code (because the where clause isn't used above)
}
if($isUpdate) {
//add ID of this object at end for where clause for use in the "update_translations.sql"
$dataValuesToSave[] = $this->id;
$dataValuesToSave[] = $this->langCode;
}
if(ModelBase::isDebug()){
error_log("dataValuesToSave: ".print_r($dataValuesToSave,true));
}
$result->success = $prepared->execute($dataValuesToSave);
if($result->success) {
if(!$isUpdate) {
if(ModelBase::isDebug()){
error_log("was an insert");
}
} else {
if(ModelBase::isDebug()){
error_log("was an update");
}
}
} else {
if(ModelBase::isDebug()){
error_log("Not successful:".print_r($result,true));
}
$result->success = false;
$result->messages[] = "Error saving \"".$this->getClassname()."\":".print_r($result,true);
}
if(!$alreadyInTransaction) {
if ($result->success) {
$pdo->commit();
} else {
$pdo->rollback();
}
}
return $result;
} catch(\PDOException $e){
$result->success = false;
$result->messages[] = "Error saving translation for \"".$this->getClassname()."\" PDOException:(".$e->getCode()."): [".$e->getMessage()."]";
if(ModelBase::isDebug()){
error_log("PDOException:(".$e->getCode()."): [".$e->getMessage()."]");
}
if(!$alreadyInTransaction) {
$pdo->rollback();
}
}
return $result;
}
//Deletes a translation for this model, from it's "_translations" table
public function DeleteTranslation(string $langCode = "", PDOHelper $source = null, $alreadyInTransaction = false):bool {
if(ModelBase::isDebug()){
error_log("----------------------------- DeleteTranslation-{$langCode}:{$this->getClassname()} -----------------------------");
}
$success = false;
if(empty($source) || !$this->isTranslatable() || !$this->idIsInteger() || (intval($this->id) <= 0) || empty($langCode)) {
return $success;
}
$pdo = $source->getPDOConnection();
$sqlLoader = $source->getSqlLoader();
$sqlPlaceholders = [
"{table_name}" => $this->getTableName(),
"{model_name}" => $this->getClassname()
];
$sql = $sqlLoader->getSingleSqlFileStatement("delete_translation", $sqlPlaceholders);
$result = $source->executeSQL($sql,[$this->id, $langCode],!$alreadyInTransaction);
$success = $result->success;
return $success;
}
public function loadByID(PDOHelper $source = null, bool $includeSecureFields = false, array $fieldsToLoad = []):bool {
if(ModelBase::isDebug()){
error_log("----------------------------- loadByID:{$this->getClassname()} -----------------------------");
}
return $this->loadBy('id', $source, $includeSecureFields, $fieldsToLoad);
}
public function loadBy(string $fieldName = "", PDOHelper $source = null, bool $includeSecureFields = false, array $fieldsToLoad = []):bool {
if(ModelBase::isDebug()){
error_log("----------------------------- loadBy ({$fieldName}):{$this->getClassname()} -----------------------------");
}
$success = false;
$props = $this->getProperties();
if(empty($source) || empty($fieldName) || !in_array($fieldName,$props) || empty($this->$fieldName)) {
return $success;
}
//ensure any passed in field names ACTUALLY are fields of this model
$filteredFieldsToLoad = $this->filterInvalidFields($fieldsToLoad);
if(empty($filteredFieldsToLoad)) {//if empty, load ALL fields
$props = $this->getProperties(true);
$filteredFieldsToLoad = $props;
}
if(!$includeSecureFields) {
$filteredFieldsToLoad = $this->filterSecureFields($filteredFieldsToLoad);
}
$keyForCache = ModelCache::getModelKey($this, $fieldName, $filteredFieldsToLoad);
$dataFromCache = ModelCache::getFromCache($keyForCache);
if(!empty($dataFromCache)){
if(ModelBase::isDebug()){
error_log("Loaded from cache. Cached object:".print_r($dataFromCache,true));
}
static::populateFromArray($this, $dataFromCache);
return true;
}
$pdo = $source->getPDOConnection();
$sqlLoader = $source->getSqlLoader();
if(ModelBase::isDebug()){
error_log("Field names to escape:".print_r($filteredFieldsToLoad,true));
}
$escapedFieldNames = static::filterExtraFields($filteredFieldsToLoad);
$escapedFieldNames = SQLLoader::escapeFieldNameArray($escapedFieldNames);
if(ModelBase::isDebug()){
error_log("Escaped field names:".print_r($escapedFieldNames,true));
}
$sqlPlaceholders = [
"{table_name}" => $this->getTableName(),
"{model_name}" => $this->getClassname(),
"{model_fields}" => empty($filteredFieldsToLoad) ? "*" : implode(',', $escapedFieldNames),
"{where_clause}" => SQLLoader::escapeFieldName($fieldName)."=?",
"{order_by}" => "id"
];
$sql = $sqlLoader->getSingleSqlFileStatement("load", $sqlPlaceholders);
if(ModelBase::isDebug()){
error_log("sql: ".$sql);
}
try {
$prepared = $pdo->prepare($sql);
$success = $prepared->execute([$this->$fieldName]);
if($success) {
$result = $prepared->fetch(\PDO::FETCH_ASSOC);
static::populateFromArray($this, $result);
$this->afterLoad($source, $filteredFieldsToLoad, $includeSecureFields);
ModelCache::putInCache($keyForCache, $result);
}
} catch(\PDOException $e){
$success = false;
if(ModelBase::isDebug()){
error_log("Exception when executing SQL:".$e->getMessage());
}
}
return $success;
}
//used to load multiple objects at once, based on a field/condition
public static function loadAllBy(PDOHelper $source, bool $includeSecureFields = false, array $fieldsToLoad = [], int $pageNum = 1, int $pageSize = 32, string $orderBy = "id", FieldCondition ...$conditions):DBResult {
if(ModelBase::isDebug()){
error_log("----------------------------- loadAllBy:" . self::getStaticClassname() . " -----------------------------");
}
$dbResult = new DBResult();
$results = [];
if(empty($source)) {
$dbResult->addMessage("The database source was invalid.");
return $dbResult;
}
if($pageNum < 1 || $pageSize < 0) {
$dbResult->addMessage("The paging parameters were invalid. PageNum: $pageNum, PageSize: $pageSize.");
return $dbResult;
}
if(ModelBase::isDebug()){
error_log("Fields to load:".print_r($fieldsToLoad,true));
}
//ensure any passed in field names ACTUALLY are fields of this model
$filteredFieldsToLoad = self::filterInvalidFields($fieldsToLoad);
if(empty($filteredFieldsToLoad)) {//if empty, load ALL fields
$props = self::getPropertiesStatic(true);
$filteredFieldsToLoad = $props;
}
if(!$includeSecureFields) {
$filteredFieldsToLoad = self::filterSecureFields($filteredFieldsToLoad);
}
$pdo = $source->getPDOConnection();
$sqlLoader = $source->getSqlLoader();
if(ModelBase::isDebug()){
error_log("Field names to escape:".print_r($filteredFieldsToLoad,true));
}
$escapedFieldNames = static::filterExtraFields($filteredFieldsToLoad);
$escapedFieldNames = SQLLoader::escapeFieldNameArray($escapedFieldNames);
if(ModelBase::isDebug()){
error_log("Escaped field names:".print_r($escapedFieldNames,true));
}
if(!FieldCondition::validateAll($conditions, true)) {
//one of the conditions failed to validate
$dbResult->addMessage("The conditions provided to \"loadAllBy\" were invalid.");
return $dbResult;//just return the current result (to avoid a db hit on already invalid parameters)
}
$whereClause = FieldCondition::combineWhereClauses($conditions);
//calculate page indices for wanted elements
$minWantedElementNumber = ($pageSize * ($pageNum-1)) + 1;
$maxWantedElementNumber = $pageSize * $pageNum;
if(ModelBase::isDebug()){
error_log("Calculated element indices for given parameters (pageNum:$pageNum, pageSize:$pageSize) - minWantedElementNumber:$minWantedElementNumber, minWantedElementNumber:$maxWantedElementNumber");
}
$sqlPlaceholders = [
"{table_name}" => self::getTableNameStatic(),
"{model_fields}" => implode(',', $escapedFieldNames),
"{model_name}" => self::getStaticClassname(),
"{where_clause}" => (empty($conditions)) ? "" : " WHERE ".$whereClause,
"{order_by}"=>$orderBy,
"{min_result_index}" => $minWantedElementNumber-1,//is an element number, we need an index (0 based)
"{max_result_index}" => $maxWantedElementNumber-1,//is an element number, we need an index (0 based)
"{max_results}" => ($pageSize === 0) ? 1000000000 : $pageSize//use 0 to signal ALL of the records after the index (a number is require here, so 1billion was simply chosen to be an arbitrarily large amount)
];
$sql = $sqlLoader->getSingleSqlFileStatement("load_all", $sqlPlaceholders);
if(ModelBase::isDebug() ){
error_log("Sql:".print_r($sql,true));
}
try {
$prepared = $pdo->prepare($sql);
//all values to put in for placeholders
$allValues = [];
foreach ($conditions as $condition) {
$fieldValue = $condition->getFieldValue();
if(is_array($fieldValue)) {
$allValues = array_merge($allValues, UtilityFunctions::flatten($fieldValue));
} else {
$allValues[] = $fieldValue;
}
}
if(ModelBase::isDebug()) {
error_log("Data values provided to SQL:".print_r($allValues,true));
}
//duplicate the values, because we have TWO where clause placeholders in our SQL
$success = $prepared->execute(array_merge($allValues,$allValues));
if($success) {
$totalResults = 0;
$numberFetched = 0;
$firstRow = true;//used to get data fetched in the rows that is the same in every row, such as aggregate data
while ($result = $prepared->fetch(\PDO::FETCH_ASSOC)) {
$numberFetched++;
if($firstRow) {
$totalResults = $result['total'];
$firstRow = false;
}
$obj = new static();
self::populateFromArray($obj, $result);
$obj->afterLoad($source, $filteredFieldsToLoad, $includeSecureFields);
$results[] = $obj;
}
$dbResult->success = true;
$dbResult->result = [
"total" => $totalResults,
"number_fetched" => $numberFetched,
"page_size" => $pageSize,
"page" => $pageNum,
"results"=>$results
];
} else {
$dbResult->addMessage("The sql execution failed, but didn't throw an exception.");
}
} catch(\PDOException $e){
if(ModelBase::isDebug()){
$msg = 'loadAllBy - Exception:' . print_r($e, true);
error_log($msg);
$dbResult->addMessage($msg);
}
}
return $dbResult;
}
//A function to execute (and can be overridden in a base class, which should call this in the base class) after loading
//This commonly is used to load fields that are FK or collections of data / format data to be used in code
protected function afterLoad(PDOHelper $source, array $fieldsToLoad = [], bool $includeSecureFields = false):bool {
$this->addProperty('langCode', 'en');
return $this->loadExtraFields($source, $includeSecureFields);
}
//Used to load extra fields after loading the main model, such as ones in a property
//This is intended to be overridden in the sub class, so that logic can be implemented that does the actual loading
protected function loadExtraFields(PDOHelper $source, bool $includeSecureFields = false):bool {return true;}
//Used to insert multiple rows into the database for the given model
public static function insertMultipleValues(PDOHelper $source, $fieldNamesToSave = [], $fieldValueCollectionsToSave = [], bool $alreadyInTransaction = false):DBResult {
if(ModelBase::isDebug()){
error_log("----------------------------- insertMultiple:".self::getStaticClassname()." -----------------------------");
}
$result = new DBResult();
if(empty($source)) {
$result->messages[] = "Source PDOHelper is invalid.";
return $result;
}
$pdo = $source->getPDOConnection();
$sqlLoader = $source->getSqlLoader();
$fieldNamesToSave = (empty($fieldNamesToSave) ? static::getPropertiesStatic() : $fieldNamesToSave);
//don't save certain properties of the base class, as they have "defaults"
$fieldsToDefault = self::geFieldNamesToDefault();
//filter these based on props we want to save (passed in, or defaulted to all model properties)
$fieldNamesToSave = array_filter($fieldNamesToSave, function($fieldName) use ($fieldsToDefault) {
return !in_array($fieldName, $fieldsToDefault) && ($fieldName !== "id"); //we don't care about the id here, as we are inserting new records
});
$filteredFields = static::filterInvalidFields($fieldNamesToSave);
$escapedFieldNames = SQLLoader::escapeFieldNameArray($filteredFields);
if(ModelBase::isDebug()){
error_log("Escaped field names:".print_r($escapedFieldNames,true));
}
//formatPlaceholders EG: (?,?), (?,?)
$formattedPlaceholdersStr = [];
$isArrayOfStr = false;
$valuesToSaveCountMismatch = false;
foreach($fieldValueCollectionsToSave as &$values) {
if(is_array($values)) {
//reorder array based on key/field names
$values = array_replace(array_flip($filteredFields), $values);
$valuesToSaveCountMismatch = (count($values) !== count($escapedFieldNames));
$formattedPlaceholdersStr[] = "(now(), now(), ".implode(", ",array_fill(0,count($values),"?") ).")";
} else {
//reorder array based on key/field names
$fieldValueCollectionsToSave = array_replace(array_flip($filteredFields), $fieldValueCollectionsToSave);
$isArrayOfStr = true;
$valuesToSaveCountMismatch = (count($fieldValueCollectionsToSave) !== count($escapedFieldNames));
$formattedPlaceholdersStr = "(now(), now(), ".implode(", ",array_fill(0,count($fieldValueCollectionsToSave),"?") ).")";
break;
}
if($valuesToSaveCountMismatch) {
break;
}
}
if($valuesToSaveCountMismatch) {
$result->addMessage("There is a different number of provided values compared to the given field names.");
return $result;
}
if(!$isArrayOfStr) {//was an array of collections of values
$formattedPlaceholdersStr = implode(",",$formattedPlaceholdersStr);
}
$sqlPlaceholders = [
"{table_name}" => self::getTableNameStatic(),
"{model_name}" => self::getStaticClassname(),
"{model_properties}" => implode(',', $escapedFieldNames),
"{placeholders}" => $formattedPlaceholdersStr
];
//this SQL ignores duplicate entries constraints (it follows them, and doesn't duplicate records, just doesn't generate errors/warnings)
$sql = $sqlLoader->getSingleSqlFileStatement("insert_multiple", $sqlPlaceholders);
try {
if(!$alreadyInTransaction) {
$pdo->beginTransaction();
}
if(ModelBase::isDebug()){
error_log("sql: ".$sql);
}
$prepared = $pdo->prepare($sql);
$flattenedValues = UtilityFunctions::flatten($fieldValueCollectionsToSave);
$result->success = $prepared->execute($flattenedValues);
if($result->success) {
} else {
if(ModelBase::isDebug()){
error_log("Not successful:".print_r($result,true));
}
$result->success = false;
$result->messages[] = "Error saving \"".self::getStaticClassname()."\":".print_r($result,true);
}
if(!$alreadyInTransaction) {
if ($result->success) {
$pdo->commit();
} else {
$pdo->rollback();
}
}
return $result;
} catch(\PDOException $e){
$result->success = false;
$result->messages[] = "Error saving \"".self::getStaticClassname()."\" PDOException:(".$e->getCode()."): [".$e->getMessage()."]";
if(ModelBase::isDebug()){
error_log("PDOException:(".$e->getCode()."): [".$e->getMessage()."]");
}
if(!$alreadyInTransaction) {
$pdo->rollback();
}
}
return $result;
}
public function save(PDOHelper $source, $fieldNamesToSave = [], bool $alreadyInTransaction = false, bool $defaultEmptyValues = true):DBResult {
if(ModelBase::isDebug()){
error_log("----------------------------- save:{$this->getClassname()} -----------------------------");