-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
Model.php
1292 lines (1105 loc) · 27.4 KB
/
Model.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao;
use Contao\Database\Result;
use Contao\Database\Statement;
use Contao\Model\Collection;
use Contao\Model\QueryBuilder;
use Contao\Model\Registry;
/**
* Reads objects from and writes them to to the database
*
* The class allows you to find and automatically join database records and to
* convert the result into objects. It also supports creating new objects and
* persisting them in the database.
*
* Usage:
*
* // Write
* $user = new UserModel();
* $user->name = 'Leo Feyer';
* $user->city = 'Wuppertal';
* $user->save();
*
* // Read
* $user = UserModel::findByCity('Wuppertal');
*
* while ($user->next())
* {
* echo $user->name;
* }
*
* @property integer $id The ID
* @property string $customTpl A custom template
*
* @author Leo Feyer <https://github.com/leofeyer>
*/
abstract class Model
{
/**
* Insert flag
*/
const INSERT = 1;
/**
* Update flag
*/
const UPDATE = 2;
/**
* Table name
* @var string
*/
protected static $strTable;
/**
* Primary key
* @var string
*/
protected static $strPk = 'id';
/**
* Class name cache
* @var array
*/
protected static $arrClassNames = array();
/**
* Data
* @var array
*/
protected $arrData = array();
/**
* Modified keys
* @var array
*/
protected $arrModified = array();
/**
* Relations
* @var array
*/
protected $arrRelations = array();
/**
* Related
* @var array
*/
protected $arrRelated = array();
/**
* Prevent saving
* @var boolean
*/
protected $blnPreventSaving = false;
/**
* Load the relations and optionally process a result set
*
* @param Result|array $objResult An optional database result or array
*/
public function __construct($objResult=null)
{
$this->arrModified = array();
$objDca = DcaExtractor::getInstance(static::$strTable);
$this->arrRelations = $objDca->getRelations();
if ($objResult !== null)
{
$arrRelated = array();
if ($objResult instanceof Result)
{
$arrData = $objResult->row();
}
else
{
$arrData = (array) $objResult;
}
// Look for joined fields
foreach ($arrData as $k=>$v)
{
if (strpos($k, '__') !== false)
{
list($key, $field) = explode('__', $k, 2);
if (!isset($arrRelated[$key]))
{
$arrRelated[$key] = array();
}
$arrRelated[$key][$field] = $v;
unset($arrData[$k]);
}
}
$objRegistry = Registry::getInstance();
$this->setRow($arrData); // see #5439
$objRegistry->register($this);
// Create the related models
foreach ($arrRelated as $key=>$row)
{
$table = $this->arrRelations[$key]['table'];
/** @var static $strClass */
$strClass = static::getClassFromTable($table);
$intPk = $strClass::getPk();
// If the primary key is empty, set null (see #5356)
if (!isset($row[$intPk]))
{
$this->arrRelated[$key] = null;
}
else
{
$objRelated = $objRegistry->fetch($table, $row[$intPk]);
if ($objRelated !== null)
{
$objRelated->mergeRow($row);
}
else
{
/** @var static $objRelated */
$objRelated = new $strClass();
$objRelated->setRow($row);
$objRegistry->register($objRelated);
}
$this->arrRelated[$key] = $objRelated;
}
}
}
}
/**
* Unset the primary key when cloning an object
*/
public function __clone()
{
$this->arrModified = array();
$this->blnPreventSaving = false;
unset($this->arrData[static::$strPk]);
}
/**
* Clone a model with its original values
*
* @return static The model
*/
public function cloneOriginal()
{
$clone = clone $this;
$clone->setRow($this->originalRow());
return $clone;
}
/**
* Set an object property
*
* @param string $strKey The property name
* @param mixed $varValue The property value
*/
public function __set($strKey, $varValue)
{
if (isset($this->arrData[$strKey]) && $this->arrData[$strKey] === $varValue)
{
return;
}
$this->markModified($strKey);
$this->arrData[$strKey] = $varValue;
unset($this->arrRelated[$strKey]);
}
/**
* Return an object property
*
* @param string $strKey The property key
*
* @return mixed|null The property value or null
*/
public function __get($strKey)
{
return $this->arrData[$strKey] ?? null;
}
/**
* Check whether a property is set
*
* @param string $strKey The property key
*
* @return boolean True if the property is set
*/
public function __isset($strKey)
{
return isset($this->arrData[$strKey]);
}
/**
* Return the name of the primary key
*
* @return string The primary key
*/
public static function getPk()
{
return static::$strPk;
}
/**
* Return an array of unique field/column names (without the PK)
*
* @return array
*/
public static function getUniqueFields()
{
$objDca = DcaExtractor::getInstance(static::getTable());
return $objDca->getUniqueFields();
}
/**
* Return the name of the related table
*
* @return string The table name
*/
public static function getTable()
{
return static::$strTable;
}
/**
* Return the current record as associative array
*
* @return array The data record
*/
public function row()
{
return $this->arrData;
}
/**
* Return the original values as associative array
*
* @return array The original data
*/
public function originalRow()
{
$row = $this->row();
if (!$this->isModified())
{
return $row;
}
$originalRow = array();
foreach ($row as $k=>$v)
{
$originalRow[$k] = $this->arrModified[$k] ?? $v;
}
return $originalRow;
}
/**
* Return true if the model has been modified
*
* @return boolean True if the model has been modified
*/
public function isModified()
{
return !empty($this->arrModified);
}
/**
* Set the current record from an array
*
* @param array $arrData The data record
*
* @return static The model object
*/
public function setRow(array $arrData)
{
foreach ($arrData as $k=>$v)
{
if (strpos($k, '__') !== false)
{
unset($arrData[$k]);
}
}
$this->arrData = $arrData;
return $this;
}
/**
* Set the current record from an array preserving modified but unsaved fields
*
* @param array $arrData The data record
*
* @return static The model object
*/
public function mergeRow(array $arrData)
{
foreach ($arrData as $k=>$v)
{
if (strpos($k, '__') !== false)
{
continue;
}
if (!isset($this->arrModified[$k]))
{
$this->arrData[$k] = $v;
}
}
return $this;
}
/**
* Mark a field as modified
*
* @param string $strKey The field key
*/
public function markModified($strKey)
{
if (!isset($this->arrModified[$strKey]))
{
$this->arrModified[$strKey] = $this->arrData[$strKey] ?? null;
}
}
/**
* Return the object instance
*
* @return static The model object
*/
public function current()
{
return $this;
}
/**
* Save the current record
*
* @return static The model object
*
* @throws \InvalidArgumentException If an argument is passed
* @throws \RuntimeException If the model cannot be saved
*/
public function save()
{
// Deprecated call
if (\func_num_args() > 0)
{
throw new \InvalidArgumentException('The $blnForceInsert argument has been removed (see system/docs/UPGRADE.md)');
}
// The instance cannot be saved
if ($this->blnPreventSaving)
{
throw new \RuntimeException('The model instance has been detached and cannot be saved');
}
$objDatabase = Database::getInstance();
$arrFields = $objDatabase->getFieldNames(static::$strTable);
// The model is in the registry
if (Registry::getInstance()->isRegistered($this))
{
$arrSet = array();
$arrRow = $this->row();
// Only update modified fields
foreach ($this->arrModified as $k=>$v)
{
// Only set fields that exist in the DB
if (\in_array($k, $arrFields))
{
$arrSet[$k] = $arrRow[$k];
}
}
$arrSet = $this->preSave($arrSet);
// No modified fields
if (empty($arrSet))
{
return $this;
}
// Track primary key changes
$intPk = $this->arrModified[static::$strPk] ?? $this->{static::$strPk};
if ($intPk === null)
{
throw new \RuntimeException('The primary key has not been set');
}
// Update the row
$objDatabase->prepare("UPDATE " . static::$strTable . " %s WHERE " . Database::quoteIdentifier(static::$strPk) . "=?")
->set($arrSet)
->execute($intPk);
$this->postSave(self::UPDATE);
$this->arrModified = array(); // reset after postSave()
}
// The model is not yet in the registry
else
{
$arrSet = $this->row();
// Remove fields that do not exist in the DB
foreach ($arrSet as $k=>$v)
{
if (!\in_array($k, $arrFields))
{
unset($arrSet[$k]);
}
}
$arrSet = $this->preSave($arrSet);
// No modified fields
if (empty($arrSet))
{
return $this;
}
// Insert a new row
$stmt = $objDatabase->prepare("INSERT INTO " . static::$strTable . " %s")
->set($arrSet)
->execute();
if (static::$strPk == 'id')
{
$this->id = $stmt->insertId;
}
$this->postSave(self::INSERT);
$this->arrModified = array(); // reset after postSave()
Registry::getInstance()->register($this);
}
return $this;
}
/**
* Modify the current row before it is stored in the database
*
* @param array $arrSet The data array
*
* @return array The modified data array
*/
protected function preSave(array $arrSet)
{
return $arrSet;
}
/**
* Modify the current row after it has been stored in the database
*
* @param integer $intType The query type (Model::INSERT or Model::UPDATE)
*/
protected function postSave($intType)
{
if ($intType == self::INSERT)
{
$this->refresh(); // might have been modified by default values or triggers
}
}
/**
* Delete the current record and return the number of affected rows
*
* @return integer The number of affected rows
*/
public function delete()
{
// Track primary key changes
$intPk = $this->arrModified[static::$strPk] ?? $this->{static::$strPk};
// Delete the row
$intAffected = Database::getInstance()->prepare("DELETE FROM " . static::$strTable . " WHERE " . Database::quoteIdentifier(static::$strPk) . "=?")
->execute($intPk)
->affectedRows;
if ($intAffected)
{
// Unregister the model
Registry::getInstance()->unregister($this);
// Remove the primary key (see #6162)
$this->arrData[static::$strPk] = null;
}
return $intAffected;
}
/**
* Lazy load related records
*
* @param string $strKey The property name
* @param array $arrOptions An optional options array
*
* @return static|Collection|null The model or a model collection if there are multiple rows
*
* @throws \Exception If $strKey is not a related field
*/
public function getRelated($strKey, array $arrOptions=array())
{
// The related model has been loaded before
if (\array_key_exists($strKey, $this->arrRelated))
{
return $this->arrRelated[$strKey];
}
// The relation does not exist
if (!isset($this->arrRelations[$strKey]))
{
$table = static::getTable();
throw new \Exception("Field $table.$strKey does not seem to be related");
}
// The relation exists but there is no reference yet (see #6161 and #458)
if (empty($this->$strKey))
{
return null;
}
$arrRelation = $this->arrRelations[$strKey];
/** @var static $strClass */
$strClass = static::getClassFromTable($arrRelation['table']);
// Load the related record(s)
if ($arrRelation['type'] == 'hasOne' || $arrRelation['type'] == 'belongsTo')
{
$this->arrRelated[$strKey] = $strClass::findOneBy($arrRelation['field'], $this->$strKey, $arrOptions);
}
elseif ($arrRelation['type'] == 'hasMany' || $arrRelation['type'] == 'belongsToMany')
{
if (isset($arrRelation['delimiter']))
{
$arrValues = StringUtil::trimsplit($arrRelation['delimiter'], $this->$strKey);
}
else
{
$arrValues = StringUtil::deserialize($this->$strKey, true);
}
$objModel = null;
if (\is_array($arrValues))
{
// Handle UUIDs (see #6525 and #8850)
if ($arrRelation['table'] == 'tl_files' && $arrRelation['field'] == 'uuid')
{
/** @var FilesModel $strClass */
$objModel = $strClass::findMultipleByUuids($arrValues, $arrOptions);
}
else
{
$strField = $arrRelation['table'] . '.' . Database::quoteIdentifier($arrRelation['field']);
$arrOptions = array_merge
(
array
(
'order' => Database::getInstance()->findInSet($strField, $arrValues)
),
$arrOptions
);
$objModel = $strClass::findBy(array($strField . " IN('" . implode("','", $arrValues) . "')"), null, $arrOptions);
}
}
$this->arrRelated[$strKey] = $objModel;
}
return $this->arrRelated[$strKey];
}
/**
* Reload the data from the database discarding all modifications
*/
public function refresh()
{
// Track primary key changes
$intPk = $this->arrModified[static::$strPk] ?? $this->{static::$strPk};
// Reload the database record
$res = Database::getInstance()->prepare("SELECT * FROM " . static::$strTable . " WHERE " . Database::quoteIdentifier(static::$strPk) . "=?")
->execute($intPk);
$this->setRow($res->row());
}
/**
* Detach the model from the registry
*
* @param boolean $blnKeepClone Keeps a clone of the model in the registry
*/
public function detach($blnKeepClone=true)
{
$registry = Registry::getInstance();
if (!$registry->isRegistered($this))
{
return;
}
$registry->unregister($this);
if ($blnKeepClone)
{
$this->cloneOriginal()->attach();
}
}
/**
* Attach the model to the registry
*/
public function attach()
{
Registry::getInstance()->register($this);
}
/**
* Called when the model is attached to the model registry
*
* @param Registry $registry The model registry
*/
public function onRegister(Registry $registry)
{
// Register aliases to unique fields
foreach (static::getUniqueFields() as $strColumn)
{
$varAliasValue = $this->{$strColumn};
if (!$registry->isRegisteredAlias($this, $strColumn, $varAliasValue))
{
$registry->registerAlias($this, $strColumn, $varAliasValue);
}
}
}
/**
* Called when the model is detached from the model registry
*
* @param Registry $registry The model registry
*/
public function onUnregister(Registry $registry)
{
// Unregister aliases to unique fields
foreach (static::getUniqueFields() as $strColumn)
{
$varAliasValue = $this->{$strColumn};
if ($registry->isRegisteredAlias($this, $strColumn, $varAliasValue))
{
$registry->unregisterAlias($this, $strColumn, $varAliasValue);
}
}
}
/**
* Prevent saving the model
*
* @param boolean $blnKeepClone Keeps a clone of the model in the registry
*/
public function preventSaving($blnKeepClone=true)
{
$this->detach($blnKeepClone);
$this->blnPreventSaving = true;
}
/**
* Find a single record by its primary key
*
* @param mixed $varValue The property value
* @param array $arrOptions An optional options array
*
* @return static The model or null if the result is empty
*/
public static function findByPk($varValue, array $arrOptions=array())
{
// Try to load from the registry
if (empty($arrOptions))
{
$objModel = Registry::getInstance()->fetch(static::$strTable, $varValue);
if ($objModel !== null)
{
return $objModel;
}
}
$arrOptions = array_merge
(
array
(
'limit' => 1,
'column' => static::$strPk,
'value' => $varValue,
'return' => 'Model'
),
$arrOptions
);
return static::find($arrOptions);
}
/**
* Find a single record by its ID or alias
*
* @param mixed $varId The ID or alias
* @param array $arrOptions An optional options array
*
* @return static The model or null if the result is empty
*/
public static function findByIdOrAlias($varId, array $arrOptions=array())
{
$isAlias = !preg_match('/^[1-9]\d*$/', $varId);
// Try to load from the registry
if (!$isAlias && empty($arrOptions))
{
$objModel = Registry::getInstance()->fetch(static::$strTable, $varId);
if ($objModel !== null)
{
return $objModel;
}
}
$t = static::$strTable;
$arrOptions = array_merge
(
array
(
'limit' => 1,
'column' => $isAlias ? array("BINARY $t.alias=?") : array("$t.id=?"),
'value' => $varId,
'return' => 'Model'
),
$arrOptions
);
return static::find($arrOptions);
}
/**
* Find multiple records by their IDs
*
* @param array $arrIds An array of IDs
* @param array $arrOptions An optional options array
*
* @return Collection|null The model collection or null if there are no records
*/
public static function findMultipleByIds($arrIds, array $arrOptions=array())
{
if (empty($arrIds) || !\is_array($arrIds))
{
return null;
}
$arrRegistered = array();
$arrUnregistered = array();
// Search for registered models
foreach ($arrIds as $intId)
{
if (empty($arrOptions))
{
$arrRegistered[$intId] = Registry::getInstance()->fetch(static::$strTable, $intId);
}
if (!isset($arrRegistered[$intId]))
{
$arrUnregistered[] = $intId;
}
}
// Fetch only the missing models from the database
if (!empty($arrUnregistered))
{
$t = static::$strTable;
$arrOptions = array_merge
(
array
(
'column' => array("$t.id IN(" . implode(',', array_map('\intval', $arrUnregistered)) . ")"),
'value' => null,
'order' => Database::getInstance()->findInSet("$t.id", $arrIds),
'return' => 'Collection'
),
$arrOptions
);
$objMissing = static::find($arrOptions);
if ($objMissing !== null)
{
foreach ($objMissing as $objCurrent)
{
$intId = $objCurrent->{static::$strPk};
$arrRegistered[$intId] = $objCurrent;
}
}
}
$arrRegistered = array_filter(array_values($arrRegistered));
if (empty($arrRegistered))
{
return null;
}
return static::createCollection($arrRegistered, static::$strTable);
}
/**
* Find a single record by various criteria
*
* @param mixed $strColumn The property name
* @param mixed $varValue The property value
* @param array $arrOptions An optional options array
*
* @return static The model or null if the result is empty
*/
public static function findOneBy($strColumn, $varValue, array $arrOptions=array())
{
$arrOptions = array_merge
(
array
(
'limit' => 1,
'column' => $strColumn,
'value' => $varValue,
'return' => 'Model'
),
$arrOptions
);
return static::find($arrOptions);
}
/**
* Find records by various criteria
*
* @param mixed $strColumn The property name
* @param mixed $varValue The property value
* @param array $arrOptions An optional options array
*
* @return static|Collection|null A model, model collection or null if the result is empty
*/
public static function findBy($strColumn, $varValue, array $arrOptions=array())
{
$blnModel = false;
$arrColumn = (array) $strColumn;
if (\count($arrColumn) == 1 && ($arrColumn[0] === static::getPk() || \in_array($arrColumn[0], static::getUniqueFields())))
{
$blnModel = true;
}
$arrOptions = array_merge
(
array
(
'column' => $strColumn,
'value' => $varValue,
'return' => $blnModel ? 'Model' : 'Collection'
),
$arrOptions
);
return static::find($arrOptions);
}
/**
* Find all records
*
* @param array $arrOptions An optional options array
*
* @return Collection|null The model collection or null if the result is empty
*/
public static function findAll(array $arrOptions=array())
{
$arrOptions = array_merge
(
array
(
'return' => 'Collection'
),
$arrOptions
);
return static::find($arrOptions);
}
/**
* Magic method to map Model::findByName() to Model::findBy('name')
*
* @param string $name The method name
* @param array $args The passed arguments
*
* @return static|Collection|integer|null A model or model collection
*
* @throws \Exception If the method name is invalid
*/
public static function __callStatic($name, $args)
{
if (strncmp($name, 'findBy', 6) === 0)
{
array_unshift($args, lcfirst(substr($name, 6)));
return static::findBy(...$args);
}
if (strncmp($name, 'findOneBy', 9) === 0)
{
array_unshift($args, lcfirst(substr($name, 9)));
return static::findOneBy(...$args);
}
if (strncmp($name, 'countBy', 7) === 0)
{
array_unshift($args, lcfirst(substr($name, 7)));
return static::countBy(...$args);