/
Model.php
1217 lines (1098 loc) · 31.5 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 Software is part of aryelgois/Medools and is provided "as is".
*
* @see LICENSE
*/
namespace aryelgois\Medools;
use aryelgois\Utils\Utils;
use aryelgois\Medools\Exceptions\{
ForeignConstraintException,
MissingColumnException,
NotForeignColumnException,
ReadOnlyModelException,
UnknownColumnException
};
/**
* Wrapper on catfan/Medoo
*
* Each model class maps to one Table in the Database, and each model object
* maps to one row.
*
* @author Aryel Mota Góis
* @license MIT
* @link https://www.github.com/aryelgois/Medools
*/
abstract class Model implements \JsonSerializable
{
/*
* Model configuration
* =========================================================================
*/
/**
* Database key in the Medools config file
*
* @const string
*/
const DATABASE = 'default';
/**
* Database's Table the model represents
*
* The recomended is to use a plural name for the table and its singular in
* the model name
*
* @const string
*/
const TABLE = '';
/**
* Columns the model expects to exist
*
* The column may be followed by a prefered data type. If not specified,
* defaults to string:
* [
* 'id [Int]',
* 'name',
* 'data [JSON]',
* ];
*
* @see \Medoo\Medoo::dataMap() For possible types
* @see getColumns() To get a columns list without types
*
* @const string[]
*/
const COLUMNS = ['id'];
/**
* Primary Key column or columns
*
* @const string[]
*/
const PRIMARY_KEY = ['id'];
/**
* Auto Increment column
*
* This column is ignored by update()
*
* @const string|null
*/
const AUTO_INCREMENT = 'id';
/**
* List of columns to receive the current timestamp automatically
*
* Values: 'auto, 'date', 'time' or 'datetime'
* Default: 'datetime'
*
* @const string[]
*/
const STAMP_COLUMNS = [];
/**
* List of optional columns
*
* List here all columns which have a default value or are nullable. You
* don't need to include implict optional columns, like AUTO_INCREMENT,
* STAMP_COLUMNS and SOFT_DELETE.
*
* @const string[]
*/
const OPTIONAL_COLUMNS = [];
/**
* Foreign Keys map
*
* A map of zero or more columns in this model, each pointing to a column in
* another model
*
* EXAMPLE:
* [
* 'local_column' => [
* 'Fully\\Qualified\\ClassName',
* 'foreign_column'
* ],
* ];
*
* @const array[]
*/
const FOREIGN_KEYS = [];
/**
* If __set(), save(), update() and delete() are disabled
*
* @const boolean
*/
const READ_ONLY = false;
/**
* If delete() actually removes the row or if it changes a column
*
* @const string|null Column affected by the soft delete
*/
const SOFT_DELETE = null;
/**
* How the soft delete works
*
* Possible values:
* - deleted: 0 or 1
* - active: 1 or 0
* - stamp: null or current timestamp
*
* @const string
*/
const SOFT_DELETE_MODE = 'deleted';
/*
* Model data
* =========================================================================
*/
/**
* Changes done by __set() to be saved by save() or update()
*
* @var mixed[]
*/
protected $changes = [];
/**
* Keeps fetched data
*
* @var mixed[]
*/
protected $data;
/**
* List of foreign models
*
* @var Model[]
*/
protected $foreign = [];
/*
* Magic methods
* =========================================================================
*/
/**
* Creates a new Model object
*
* @param mixed $where @see load(). If null, a fresh model is created
*
* @throws \InvalidArgumentException If could not load from Database
*/
public function __construct($where = null)
{
if ($where !== null && !$this->load($where)) {
$message = 'Could not load ' . static::class . ' from Database';
throw new \InvalidArgumentException($message);
}
}
/**
* Returns the stored data in a column
*
* If a Foreign column is requested, returns the corresponding Model instead
*
* @param string $column A known column
*
* @return mixed
*
* @throws UnknownColumnException @see checkUnknownColumn()
* @throws ForeignConstraintException @see loadForeign()
*/
public function __get($column)
{
static::checkUnknownColumn($column);
if (array_key_exists($column, $this->changes)
&& $this->changes[$column] === null
) {
return null;
}
$value = $this->changes[$column] ?? $this->data[$column];
if (array_key_exists($column, static::FOREIGN_KEYS)) {
if (!array_key_exists($column, $this->foreign)) {
$this->loadForeign($column, $value);
}
return $this->foreign[$column] ?? null;
}
return $value;
}
/**
* Checks if a column has some value
*
* @param string $column A known column
*
* @return boolean
*
* @throws UnknownColumnException @see __get()
*/
public function __isset($column)
{
return null !== $this->__get($column);
}
/**
* Changes the value in a column
*
* NOTE:
* - Changes need to be saved in the Database with save() or update($column)
* - You can not assign a foreign model that was not saved yet
*
* @param string $column A known column
* @param mixed $value The new value
*
* @throws ReadOnlyModelException @see checkReadOnly()
* @throws UnknownColumnException @see checkUnknownColumn()
* @throws ForeignConstraintException
*/
public function __set($column, $value)
{
static::checkReadOnly();
static::checkUnknownColumn($column);
$value = $this->onColumnChange($column, $value);
if (array_key_exists($column, static::FOREIGN_KEYS)) {
$foreign_map = static::FOREIGN_KEYS[$column];
if ($value instanceof $foreign_map[0]) {
if ($value->isFresh()) {
throw new ForeignConstraintException(
static::class,
$column
);
}
$this->foreign[$column] = $value;
$this->changes[$column] = $value->data[$foreign_map[1]];
return;
} else {
$this->loadForeign($column, $value);
}
}
$this->changes[$column] = $value;
}
/**
* Sets a column to NULL
*
* @see __set()
*
* @param string $column A known column
*
* @throws ReadOnlyModelException @see __set()
* @throws UnknownColumnException @see __set()
* @throws ForeignConstraintException
*/
public function __unset($column)
{
$this->__set($column, null);
}
/**
* Exports the Model to the ModelManager after unserialize()
*/
public function __wakeup()
{
$this->managerExport();
}
/*
* CRUD methods
* =========================================================================
*/
/**
* Creates a new row in the Table or updates it with new data
*
* @see validate() Throws
*
* @return true On success
* @return null On pre-save failure
* @return false On post-save failure
* @return string On Database failure @see http://php.net/pdo.errorcode
*
* @throws ReadOnlyModelException @see checkReadOnly()
*/
public function save()
{
static::checkReadOnly();
$is_fresh = $this->isFresh();
$this->updateStampColumns();
if (($is_fresh && !$this->onFirstSave())
|| !$this->onSave()
|| empty($this->changes)
) {
return;
}
$data = $this->changes;
$data = static::validate($data, $is_fresh);
$database = self::getDatabase();
$stmt = ($is_fresh)
? $database->insert(static::TABLE, $data)
: $database->update(static::TABLE, $data, $this->getPrimaryKey());
$error_code = $stmt->errorCode();
if ($error_code == '00000') {
/*
* It is prefered to load back because the Database may apply
* default values or alter some columns. Also, it forces updating
* foreign models.
*
* - If it was a fresh model with AUTO_INCREMENT, get the new value
* - Extract the PRIMARY_KEY
* - Load from Database
*/
$data = $this->getData();
if ($is_fresh) {
$column = static::AUTO_INCREMENT;
if ($column !== null) {
$data[$column] = $database->id();
}
}
$where = Utils::arrayWhitelist($data, static::PRIMARY_KEY);
return $this->load($where);
}
return $error_code;
}
/**
* Loads a row from Table into the model
*
* @param mixed $where Value for Primary Key or \Medoo\Medoo where clause
*
* @return boolean For success or failure
*
* @throws \InvalidArgumentException @see processWhere()
*/
public function load($where)
{
$where = self::processWhere($where);
$old_primary_key = $this->getPrimaryKey();
$database = self::getDatabase();
$data = $database->get(static::TABLE, static::COLUMNS, $where);
if ($data) {
$this->reset();
$this->data = $data;
if ($old_primary_key) {
$this->managerUpdate($old_primary_key);
} else {
$this->managerExport();
}
return true;
}
return false;
}
/**
* Selectively updates the model's row in the Database
*
* @see validate() Throws
*
* @param string|string[] $columns Specify which columns to update
*
* @return true On success
* @return false On post-update failure
* @return string On Database failure @see http://php.net/pdo.errorcode
*
* @throws ReadOnlyModelException @see checkReadOnly()
* @throws \LogicException If trying to update a fresh Model
*/
public function update($columns)
{
static::checkReadOnly();
if ($this->isFresh()) {
$message = 'Can not update fresh Model: ' . static::class;
throw new \LogicException($message);
}
$this->updateStampColumns($columns);
$columns = (array) $columns;
$data = Utils::arrayWhitelist($this->changes, $columns);
$data = static::validate($data, false);
$database = self::getDatabase();
$stmt = $database->update(static::TABLE, $data, $this->getPrimaryKey());
$error_code = $stmt->errorCode();
if ($error_code == '00000') {
$changes = Utils::arrayBlacklist($this->changes, $columns);
$data = $this->getData();
$where = Utils::arrayWhitelist($data, static::PRIMARY_KEY);
if ($this->load($where)) {
$this->changes = $changes;
return true;
}
return false;
}
return $error_code;
}
/**
* Removes model's row from the Table or sets the SOFT_DELETE column
*
* @return boolean For success or failure
*
* @throws ReadOnlyModelException @see checkReadOnly()
* @throws \LogicException If SOFT_DELETE_MODE is unknown
*/
public function delete()
{
static::checkReadOnly();
$column = static::SOFT_DELETE;
if ($column) {
switch (static::SOFT_DELETE_MODE) {
case 'deleted':
$value = 1;
break;
case 'active':
$value = 0;
break;
case 'stamp':
$value = static::getCurrentTimestamp();
break;
default:
throw new \LogicException(sprintf(
"%s has invalid SOFT_DELETE_MODE mode: '%s'",
static::class,
static::SOFT_DELETE_MODE
));
break;
}
$this->__set($column, $value);
if ($this->isFresh()) {
return true;
}
return $this->update($column);
}
$database = self::getDatabase();
$stmt = $database->delete(static::TABLE, $this->getPrimaryKey());
if ($stmt->rowCount() > 0) {
ModelManager::remove($this);
$this->reset();
return true;
}
return false;
}
/*
* Basic methods
* =========================================================================
*/
/**
* Returns data in model's Table
*
* @param mixed[] $where \Medoo\Medoo where clause
* @param string[] $columns Specify which columns you want
*
* @return array[]
*
* @throws UnknownColumnException If any item in $columns is invalid
* @see getTypedColumns()
*/
public static function dump($where = [], $columns = [])
{
$columns = (empty($columns))
? static::COLUMNS
: array_values(self::getTypedColumns($columns));
$database = self::getDatabase();
return $database->select(static::TABLE, $columns, $where);
}
/**
* Changes the value in multiple columns
*
* Very useful when chaining __construct()
*
* Example:
*
* $model = (new My\Model)->fill([
* 'column' => 'value',
* ]);
*
* @param mixed[] $data An array of known columns => value
*
* @return $this
*
* @throws ... same as __set()
*/
public function fill(array $data)
{
foreach ($data as $column => $value) {
$this->__set($column, $value);
}
return $this;
}
/**
* Returns list of changed columns
*
* @return string[]
*/
public function getChangedColumns()
{
return array_keys($this->changes);
}
/**
* Returns columns list without data type
*
* @return string[]
*/
final public static function getColumns()
{
$result = [];
foreach (static::COLUMNS as $column) {
$result[] = trim(explode('[', $column, 2)[0]);
}
return $result;
}
/**
* Selects Current Timestamp from Database
*
* Useful to keep timezone consistent
*
* @return string
*/
public static function getCurrentTimestamp()
{
$database = self::getDatabase();
$sql = 'SELECT CURRENT_TIMESTAMP';
return $database->query($sql)->fetch(\PDO::FETCH_NUM)[0];
}
/**
* Returns currently stored data
*
* @return mixed[]
*/
final public function getData()
{
return array_replace($this->data ?? [], $this->changes);
}
/**
* Returns a database connection
*
* @return \Medoo\Medoo
*/
final public static function getDatabase()
{
return MedooConnection::getInstance(static::DATABASE);
}
/**
* Safely loads a model
*
* If an instance for the desired model already exists, it is returned,
* otherwise creates a new one
*
* @param mixed $where @see load()
*
* @return Model
*/
final public static function getInstance($where)
{
return ModelManager::getInstance(static::class, $where);
}
/**
* Shortcut for ModelIterator
*
* @param mixed $where @see ModelIterator::__construct()
*
* @return ModelIterator of this Model
*/
final public static function getIterator($where)
{
return new ModelIterator(static::class, $where);
}
/**
* Returns model's Primary Key
*
* NOTE:
* - It returns the data saved in Database, changes by __set() are ignored
*
* @return mixed[] Usually it will contain an integer key
* @return null If the model was not saved yet
*/
public function getPrimaryKey()
{
if ($this->isFresh()) {
return null;
}
return Utils::arrayWhitelist($this->data, static::PRIMARY_KEY);
}
/**
* Returns columns with their data types (when defined)
*
* @param string|string[] $columns Columns to receive its type
*
* @return string|string[]
*
* @throws UnknownColumnException If any item in $columns is invalid
* @see checkUnknownColumn()
*/
final public static function getTypedColumns($columns)
{
static::checkUnknownColumn($columns);
$result = Utils::arrayWhitelist(
array_combine(self::getColumns(), static::COLUMNS),
(array) $columns
);
return (is_string($columns))
? array_values($result)[0]
: $result;
}
/**
* Tells if Model is deleted
*
* It is useful when the Model has a SOFT_DELETE column
*
* @return boolean
*
* @throws \LogicException If SOFT_DELETE_MODE is unknown
*/
final public function isDeleted()
{
$column = static::SOFT_DELETE;
if ($column) {
$value = $this->__get($column);
switch (static::SOFT_DELETE_MODE) {
case 'deleted':
$result = (int) $value === 1;
break;
case 'active':
$result = (int) $value === 0;
break;
case 'stamp':
$result = $value !== null;
break;
default:
throw new \LogicException(sprintf(
"%s has invalid SOFT_DELETE_MODE mode: '%s'",
static::class,
static::SOFT_DELETE_MODE
));
break;
}
return $result;
}
return false;
}
/**
* Tells if the object is a new Model
*
* @return boolean
*/
final public function isFresh()
{
return $this->data === null;
}
/**
* Reloads model data
*
* @return boolean For success or failure
*/
public function reload()
{
return $this->load($this->getPrimaryKey());
}
/**
* Converts the Model to array
*
* NOTE:
* - Loads all foreigns recursively
*
* @return mixed[]
*/
public function toArray()
{
return json_decode(json_encode($this), true);
}
/**
* Sets the SOFT_DELETE column to a undeleted state
*
* @return boolean For success or failure
*
* @throws ReadOnlyModelException @see checkReadOnly()
* @throws \LogicException If the Model is not soft-deletable
* @throws \LogicException If SOFT_DELETE_MODE is unknown
*/
public function undelete()
{
static::checkReadOnly();
$column = static::SOFT_DELETE;
if ($column) {
switch (static::SOFT_DELETE_MODE) {
case 'deleted':
$value = 0;
break;
case 'active':
$value = 1;
break;
case 'stamp':
$value = null;
break;
default:
throw new \LogicException(sprintf(
"%s has invalid SOFT_DELETE_MODE mode: '%s'",
static::class,
static::SOFT_DELETE_MODE
));
break;
}
$this->__set($column, $value);
if ($this->isFresh()) {
return true;
}
return $this->update($column);
}
$message = 'Model ' . static::class . ' is not soft-deletable';
throw new \LogicException($message);
}
/**
* Removes changes
*
* Pass a column name to only remove that column, otherwise it removes all
* changes
*
* @param string $column Which column to undo
*
* @throws UnknownColumnException @see checkUnknownColumn()
*/
public function undo(string $column = null)
{
if ($column === null) {
$this->changes = [];
} else {
static::checkUnknownColumn($column);
unset($this->changes[$column]);
}
}
/*
* Internal methods
* =========================================================================
*/
/**
* Adds column types in array's keys
*
* @param mixed[] $data With keys as column names
*
* @return mixed[] With keys including the column type
*/
final public static function addColumnTypeKeys(array $data)
{
$columns = self::getTypedColumns(array_keys($data));
return array_combine($columns, array_merge($columns, $data));
}
/**
* Tests if model is READ_ONLY
*
* @throws ReadOnlyModelException
*/
final public static function checkReadOnly()
{
if (static::READ_ONLY) {
throw new ReadOnlyModelException(static::class);
}
}
/**
* Tests if model has columns
*
* @param string|string[] $columns List of columns to test
*
* @throws UnknownColumnException
*/
final public static function checkUnknownColumn($columns)
{
$unknown = array_diff((array) $columns, self::getColumns());
if (!empty($unknown)) {
throw new UnknownColumnException(static::class, $unknown);
}
}
/**
* Returns STAMP_COLUMNS with 'auto' mode
*
* @return string[]
*/
public static function getAutoStampColumns()
{
$auto_stamp = [];
if (!empty(static::STAMP_COLUMNS)) {
$stamp_columns = self::normalizeColumnList(static::STAMP_COLUMNS);
$auto_stamp = array_filter($stamp_columns, function ($mode) {
return $mode === 'auto';
});
}
return array_keys($auto_stamp);
}
/**
* Returns required columns
*
* @return string[]
*/
public static function getRequiredColumns()
{
return array_values(array_diff(
self::getColumns(),
static::OPTIONAL_COLUMNS,
// implicit optional columns:
[
static::AUTO_INCREMENT,
static::SOFT_DELETE,
],
static::getStampColumns()
));
}
/**
* Returns normalized keys for STAMP_COLUMNS
*
* @return string[]
*/
public static function getStampColumns()
{
return array_keys(self::normalizeColumnList(static::STAMP_COLUMNS));
}
/**
* Returns the stored data
*
* NOTE:
* - Expands foreign models
*
* @return mixed[]
* @return null If no columns are filled
*/
public function jsonSerialize()
{
$data = $this->getData();
if (empty($data)) {
return null;
}
foreach (array_keys(static::FOREIGN_KEYS) as $column) {
$data[$column] = $this->__get($column);
}
return $data;
}
/**
* Updates a foreign model to a new row
*
* It tests if $column is a valid foreign column
*
* @param string $column A column in FOREIGN_KEYS keys
* @param mixed $value A value in the foreign table
*
* @throws UnknownColumnException @see checkUnknownColumn()
* @throws NotForeignColumnException
* @throws ForeignConstraintException
*/
protected function loadForeign($column, $value)
{
static::checkUnknownColumn($column);
if (!array_key_exists($column, static::FOREIGN_KEYS)) {
throw new NotForeignColumnException(static::class, $column);
}
$foreign_map = static::FOREIGN_KEYS[$column];
if ($value === null) {
unset($this->foreign[$column]);
return;
}
$foreign = ModelManager::getInstance(
$foreign_map[0],
[$foreign_map[1] => $value]
);
if ($foreign) {
$this->foreign[$column] = $foreign;
} else {
throw new ForeignConstraintException(static::class, $column);
}
}
/**
* Exports this Model to ModelManager
*
* @return boolean For success or failure
*/
protected function managerExport()
{
ModelManager::import($this);
}
/**
* Updates this Model in the ModelManager
*
* @param string[] $old_primary_key
*/
protected function managerUpdate($old_primary_key)
{
ModelManager::remove(array_merge([static::class], $old_primary_key));
$this->managerExport();
}
/**
* Normalize column lists
*
* EXAMPLE:
* $list = [
* 'column_a',
* 'column_b' => value,
* ];
*
* return [