forked from php-activerecord/activerecord
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.php
More file actions
1898 lines (1673 loc) · 51.4 KB
/
Model.php
File metadata and controls
1898 lines (1673 loc) · 51.4 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
/**
* The base class for your models.
*
* @package ActiveRecord
*/
namespace ActiveRecord;
use ActiveRecord\Exception\ActiveRecordException;
use ActiveRecord\Exception\ReadOnlyException;
use ActiveRecord\Exception\RelationshipException;
use ActiveRecord\Exception\UndefinedPropertyException;
use ActiveRecord\Relationship\AbstractRelationship;
use ActiveRecord\Relationship\HasAndBelongsToMany;
use ActiveRecord\Relationship\HasMany;
use ActiveRecord\Serialize\JsonSerializer;
use ActiveRecord\Serialize\Serialization;
/**
* The base class for your models.
* Defining an ActiveRecord model for a table called people and orders:
*
* ```sql
* CREATE TABLE people(
* id int primary key auto_increment,
* parent_id int,
* first_name varchar(50),
* last_name varchar(50)
* );
*
* CREATE TABLE orders(
* id int primary key auto_increment,
* person_id int not null,
* cost decimal(10,2),
* total decimal(10,2)
* );
* ```
*
* ```php
* class Person extends ActiveRecord\Model {
* static array $belongs_to = [
* 'parent' => [
* 'foreign_key' => 'parent_id',
* 'class_name' => 'Person'
* ]
* ];
*
* static array $has_many = [
* 'children' => [
* 'foreign_key' => 'parent_id',
* 'class_name' => 'Person'
* ],
* 'orders' => true
* ];
*
* static $validates_length_of = [
* 'first_name' => ['within' => [1,50]],
* 'last_name' => [1,50]
* );
* }
*
* class Order extends ActiveRecord\Model {
* static array $belongs_to = [
* 'person' => true
* ];
*
* static $validates_numericality_of = [
* 'cost' => ['greater_than' => 0],
* 'total' => ['greater_than' => 0]
* );
*
* static $before_save = ['calculate_total_with_tax'];
*
* public function calculate_total_with_tax() {
* $this->total = $this->cost * 0.045;
* }
* }
* ```
*
* For a more in-depth look at defining models, relationships, callbacks and many other things
* please consult our {@link http://www.phpactiverecord.org/guides Guides}.
*
* @phpstan-import-type HasManyOptions from Types
* @phpstan-import-type HasAndBelongsToManyOptions from Types
* @phpstan-import-type BelongsToOptions from Types
* @phpstan-import-type SerializeOptions from Serialize\Serialization
* @phpstan-import-type ValidationOptions from Validations
* @phpstan-import-type ValidateInclusionOptions from Validations
* @phpstan-import-type ValidateLengthOptions from Validations
* @phpstan-import-type ValidateFormatOptions from Validations
* @phpstan-import-type ValidateUniquenessOptions from Validations
* @phpstan-import-type ValidateNumericOptions from Validations
*
* @package ActiveRecord
*
* @phpstan-import-type Attributes from Types
* @phpstan-import-type PrimaryKey from Types
* @phpstan-import-type QueryOptions from Types
* @phpstan-import-type DelegateOptions from Types
* @phpstan-import-type RelationOptions from Types
*
* @see BelongsTo
* @see CallBack
* @see HasMany
* @see HasAndBelongsToMany
* @see Serialization
* @see Validations
*/
class Model
{
/**
* An instance of {@link ValidationErrors} and will be instantiated once a write method is called.
*/
public ValidationErrors $errors;
/**
* Contains model values as column_name => value
*
* @var Attributes
*/
private array $attributes = [];
/**
* Flag whether this model's attributes have been modified since it will either be null or an array of column_names that have been modified
*
* @var array<string, bool>
*/
private array $__dirty = [];
/**
* Flag that determines of this model can have a writer method invoked such as: save/update/insert/delete
*/
private bool $__readonly = false;
/**
* Array of relationship objects as model_attribute_name => relationship
*
* @var array<string, Model|array<Model>|null>
*/
private array $__relationships = [];
/**
* Flag that determines if a call to save() should issue an insert or an update sql statement
*/
private bool $__new_record = true;
/**
* Set to the name of the connection this {@link Model} should use.
*/
public static string $connection;
/**
* Set to the name of the database this Model's table is in.
*/
public static string $db;
/**
* Set this to explicitly specify the model's table name if different from inferred name.
*
* If your table doesn't follow our table name convention you can set this to the
* name of your table to explicitly tell ActiveRecord what your table is called.
*/
public static string $table_name;
/**
* Set this to override the default primary key name if different from default name of "id".
*/
public static string $primary_key;
/**
* Set this to explicitly specify the sequence name for the table.
*/
public static string $sequence;
/**
* Set this to true in your subclass to use caching for this model. Note that you must also configure a cache object.
*/
public static bool $cache = false;
/**
* Set this to specify an expiration period for this model. If not set, the expire value you set in your cache options will be used.
*
* @var int
*/
public static $cache_expire;
/**
* @var ValidationOptions
*/
public static array $validates_presence_of;
/**
* @var array<string, ValidateFormatOptions>
*/
public static array $validates_format_of;
/**
* @var array<string,ValidateInclusionOptions>
*/
public static array $validates_inclusion_of;
/**
* @var array<string,ValidateInclusionOptions>
*/
public static array $validates_exclusion_of;
/**
* @var array<string, ValidateUniquenessOptions>
*/
public static array $validates_uniqueness_of;
/**
* @var array<string, ValidateNumericOptions>
*/
public static array $validates_numericality_of;
/**
* @var ValidateLengthOptions
*/
public static array $validates_length_of;
/**
* @var array<string,HasManyOptions>
*/
public static array $has_many;
/**
* @var array<string, HasAndBelongsToManyOptions>
*/
public static array $has_and_belongs_to_many;
/**
* @var array<string,HasManyOptions>
*/
public static array $has_one;
/**
* @var array<string,BelongsToOptions>
*/
public static array $belongs_to;
/**
* Allows you to create aliases for attributes.
*
* ```
* class Person extends ActiveRecord\Model {
* static $alias_attribute = [
* 'alias_first_name' => 'first_name',
* 'alias_last_name' => 'last_name'
* ];
* }
*
* $person = Person::first();
* $person->alias_first_name = 'Tito';
* echo $person->alias_first_name;
* ```
*
* @var array<string,string>
*/
public static array $alias_attribute = [];
/**
* Whitelist of attributes that are checked from mass-assignment calls such as constructing a model or using update_attributes.
*
* This is the opposite of {@link attr_protected $attr_protected}.
*
* ```
* class Person extends ActiveRecord\Model {
* static $attr_accessible = [
* 'first_name',
* 'last_name'
* ];
* }
*
* $person = new Person([
* 'first_name' => 'Tito',
* 'last_name' => 'the Grief',
* 'id' => 11111
* ]);
*
* echo $person->id; # => null
* ```
*
* @var list<string>
*/
public static array $attr_accessible = [];
/**
* Blacklist of attributes that cannot be mass-assigned.
*
* This is the opposite of {@link attr_accessible $attr_accessible} and the format
* for defining these are exactly the same.
*
* If the attribute is both accessible and protected, it is treated as protected.
*
* @var array<string>
*/
public static array $attr_protected = [];
/**
* Delegates calls to a relationship.
*
* ```
* class Person extends ActiveRecord\Model {
* static array $belongs_to = [
* 'venue' => true,
* 'host' => true
* ];
* static $delegate = [
* [
* 'attributes' => [
* 'name',
* 'state'
* ],
* 'to' => 'venue'
* ],
* [
* 'attributes' => [
* 'name'
* ],
* 'to' => 'host',
* 'prefix' => 'woot'
* ];
* ]
* ```
*
* Can then do:
*
* ```
* $person->state // same as calling $person->venue->state
* $person->name // same as calling $person->venue->name
* $person->woot_name // same as calling $person->host->name
* ```
*
* @var array<DelegateOptions>
*/
public static array $delegate = [];
/**
* Constructs a model.
*
* When a user instantiates a new object (e.g.: it was not ActiveRecord that instantiated via a find)
* then @var $attributes will be mapped according to the schema's defaults. Otherwise, the given
* $attributes will be mapped via set_attributes_via_mass_assignment.
*
* ```
* new Person([
* 'first_name' => 'Tito',
* 'last_name' => 'the Grief'
* ]);
* ```
*
* @param Attributes $attributes Hash containing names and values to mass assign to the model
* @param bool $guard_attributes Set to true to guard protected/non-accessible attributes
* @param bool $instantiating_via_find Set to true if this model is being created from a find call
* @param bool $new_record Set to true if this should be considered a new record
*/
public function __construct(array $attributes = [], bool $guard_attributes = true, bool $instantiating_via_find = false, bool $new_record = true)
{
$this->__new_record = $new_record;
// initialize attributes applying defaults
if (!$instantiating_via_find) {
foreach (static::table()->columns as $name => $meta) {
$this->attributes[$meta->inflected_name] = $meta->default ?? null;
}
}
$this->set_attributes_via_mass_assignment($attributes, $guard_attributes);
// since all attribute assignment now goes thru assign_attributes() we want to reset
// dirty if instantiating via find since nothing is really dirty when doing that
if ($instantiating_via_find) {
$this->__dirty = [];
}
$this->invoke_callback('after_construct', false);
}
/**
* Magic method which delegates to read_attribute(). This handles firing off getter methods,
* as they are not checked/invoked inside of read_attribute(). This circumvents the problem with
* a getter being accessed with the same name as an actual attribute.
*
* You can also define customer getter methods for the model.
*
* EXAMPLE:
* ```
* class User extends ActiveRecord\Model {
*
* # define custom getter methods. Note you must
* # prepend get_ to your method name:
* function get_middle_initial() {
* return $this->middle_name{0};
* }
* }
*
* $user = new User();
* echo $user->middle_name; # will call $user->get_middle_name()
* ```
*
* If you define a custom getter with the same name as an attribute then you
* will need to use read_attribute() to get the attribute's value.
* This is necessary due to the way __get() works.
*
* For example, assume 'name' is a field on the table and we're defining a
* custom getter for 'name':
*
* ```
* class User extends ActiveRecord\Model {
*
* # INCORRECT way to do it
* # function get_name() {
* # return strtoupper($this->name);
* # }
*
* function get_name() {
* return strtoupper($this->read_attribute('name'));
* }
* }
*
* $user = new User();
* $user->name = 'bob';
* echo $user->name; # => BOB
* ```
*
* @see read_attribute()
*
* @param string $name Name of an attribute
*
* @return mixed The value of the attribute
*/
public function &__get($name)
{
// check for getter
$name = strtolower($name);
if (method_exists($this, "get_$name")) {
$name = "get_$name";
$callable = [$this, $name];
assert(is_callable($callable));
$res = call_user_func($callable);
return $res;
}
return $this->read_attribute($name);
}
/**
* Determines if an attribute exists for this {@link Model}.
*
* @param string $attribute_name
*
* @return bool
*/
public function __isset($attribute_name)
{
// check for aliased attribute
if (array_key_exists($attribute_name, static::$alias_attribute)) {
return true;
}
// check for attribute
if (array_key_exists($attribute_name, $this->attributes)) {
return true;
}
// check for getters
if (method_exists($this, "get_{$attribute_name}")) {
return true;
}
// check for relationships
if (static::table()->has_relationship($attribute_name)) {
return true;
}
return false;
}
/**
* Magic allows un-defined attributes to set via $attributes.
*
* You can also define customer setter methods for the model.
*
* EXAMPLE:
* ```
* class User extends ActiveRecord\Model {
*
* # define custom setter methods. Note you must
* # prepend set_ to your method name:
* function set_password($plaintext) {
* $this->encrypted_password = md5($plaintext);
* }
* }
*
* $user = new User();
* $user->password = 'plaintext'; # will call $user->set_password('plaintext')
* ```
*
* If you define a custom setter with the same name as an attribute then you
* will need to use assign_attribute() to assign the value to the attribute.
* This is necessary due to the way __set() works.
*
* For example, assume 'name' is a field on the table and we're defining a
* custom setter for 'name':
*
* ```
* class User extends ActiveRecord\Model {
*
* // INCORRECT way to do it
* // function set_name($name) {
* // $this->name = strtoupper($name);
* // }
*
* function set_name($name) {
* $this->assign_attribute('name',strtoupper($name));
* }
* }
*
* $user = new User();
* $user->name = 'bob';
* echo $user->name; # => BOB
* ```
*
* @param $name string Name of attribute, relationship or other to set
* @param $value mixed The value
*
* @throws UndefinedPropertyException if $name does not exist
*/
public function __set(string $name, mixed $value): void
{
$name = strtolower($name);
if (array_key_exists($name, static::$alias_attribute)) {
$name = static::$alias_attribute[$name];
} elseif (method_exists($this, "set_$name")) {
$name = "set_$name";
$this->$name($value);
return;
}
if (array_key_exists($name, $this->attributes)) {
$this->assign_attribute($name, $value);
return;
}
if ('id' == $name) {
$this->assign_attribute($this->get_primary_key(), $value);
return;
}
foreach (static::$delegate as $key => $item) {
if ($delegated_name = $this->is_delegated($name, $item)) {
$this->{$item['to']}->$delegated_name = $value;
return;
}
}
throw new UndefinedPropertyException(get_called_class(), $name);
}
/**
* Magic method; this gets called by PHP itself when your model is unserialized.
*/
public function __wakeup()
{
// make sure the models Table instance gets initialized when waking up
static::table();
}
/**
* Assign a value to an attribute.
*
* @param string $name Name of the attribute
* @param mixed $value Value of the attribute
*
* @return mixed the attribute value
*/
public function assign_attribute($name, $value)
{
$table = static::table();
if (!is_object($value)) {
if (array_key_exists($name, $table->columns)) {
$value = $table->columns[$name]->cast($value, static::connection());
} else {
$col = $table->get_column_by_inflected_name($name);
if (!is_null($col)) {
$value = $col->cast($value, static::connection());
}
}
}
// convert php's \DateTime to ours
if ($value instanceof \DateTime) {
$date_class = Config::instance()->get_date_class();
if (!($value instanceof $date_class)) {
$value = $date_class::createFromFormat(
Connection::DATETIME_TRANSLATE_FORMAT,
$value->format(Connection::DATETIME_TRANSLATE_FORMAT),
$value->getTimezone()
);
}
}
if ($value instanceof DateTimeInterface) {
// Tell the Date object that it's associated with this model and attribute. This is so it
// has the ability to flag this model as dirty if a field in the Date object changes.
$value->attribute_of($this, $name);
}
$this->attributes[$name] = $value;
$this->flag_dirty($name);
return $value;
}
/**
* Retrieves an attribute's value or a relationship object based on the name passed. If the attribute
* accessed is 'id' then it will return the model's primary key no matter what the actual attribute name is
* for the primary key.
*
* @param $name Name of an attribute
*
* @throws UndefinedPropertyException if name could not be resolved to an attribute, relationship, ...
*
* @return mixed The value of the attribute
*/
public function &read_attribute(string $name)
{
// check for aliased attribute
if (array_key_exists($name, static::$alias_attribute)) {
$name = static::$alias_attribute[$name];
}
// check for attribute
if (array_key_exists($name, $this->attributes)) {
return $this->attributes[$name];
}
// check relationships if no attribute
if (array_key_exists($name, $this->__relationships)) {
return $this->__relationships[$name];
}
$table = static::table();
// this may be first access to the relationship so check Table
if ($table->get_relationship($name)) {
$res = $this->initRelationships($name);
return $res;
}
if ('id' == $name) {
$pk = $this->get_primary_key();
if (isset($this->attributes[$pk])) {
return $this->attributes[$pk];
}
}
// do not remove - have to return null by reference in strict mode
$null = null;
foreach (static::$delegate as $delegateName => $item) {
if ($delegated_name = $this->is_delegated($name, $item)) {
$to = $item['to'];
if ($this->$to) {
$val = &$this->$to->__get($delegated_name);
return $val;
}
return $null;
}
}
throw new UndefinedPropertyException(get_called_class(), $name);
}
/**
* @throws RelationshipException
*
* @return Model|array<Model>|null
*/
protected function initRelationships(string $name): Model|array|null
{
$table = static::table();
$relationship = $table->get_relationship($name);
if (null !== $relationship) {
$this->__relationships[$name] = $relationship->load($this);
}
return $this->__relationships[$name] ?? null;
}
/**
* Flags an attribute as dirty.
*/
public function flag_dirty(string $attribute): void
{
$this->__dirty[$attribute] = true;
}
/**
* Returns hash of attributes that have been modified since loading the model.
*
* @return Attributes
*/
public function dirty_attributes(): array
{
if (count($this->__dirty) <= 0) {
return [];
}
return array_intersect_key($this->attributes, $this->__dirty);
}
/**
* Check if a particular attribute has been modified since loading the model.
*
* @param string $attribute Name of the attribute
*
* @return bool tRUE if it has been modified
*/
public function attribute_is_dirty($attribute)
{
return $this->__dirty && isset($this->__dirty[$attribute]) && array_key_exists($attribute, $this->attributes);
}
/**
* Returns a copy of the model's attributes hash.
*
* @return Attributes A copy of the model's attribute data
*/
public function attributes(): array
{
return $this->attributes;
}
public function get_primary_key(): string
{
$pk = static::table()->pk;
return $pk[0];
}
/**
* Returns the actual attribute name if $name is aliased.
*/
public function get_real_attribute_name(string $name): ?string
{
if (array_key_exists($name, $this->attributes)) {
return $name;
}
if (array_key_exists($name, static::$alias_attribute)) {
return static::$alias_attribute[$name];
}
return null;
}
/**
* Returns array of validator data for this Model.
*
* Will return an array looking like:
*
* ```
* [
* 'name' => [
* [
* 'validator' => 'validates_presence_of'
* ],
* [
* 'validator' => 'validates_inclusion_of',
* 'in' => ['Bob','Joe','John']
* ]
* ],
* 'password' => [
* [
* 'validator' => 'validates_length_of',
* 'minimum' => 6
* ]
* ]
* ];
* ```
*
* @return array<string, array<mixed>> an array containing validator data for this model
*/
public function get_validation_rules(): array
{
$validator = new Validations($this);
return $validator->rules();
}
/**
* Returns an associative array containing values for all the attributes in $attributes
*
* @param list<string> $attributes Array containing attribute names
*
* @return Attributes A hash containing $name => $value
*/
public function get_values_for(array $attributes): array
{
$ret = [];
foreach ($attributes as $name) {
if (array_key_exists($name, $this->attributes)) {
$ret[$name] = $this->attributes[$name];
}
}
return $ret;
}
/**
* Retrieves the name of the table for this Model.
*
* @return string
*/
public static function table_name()
{
return static::table()->table;
}
/**
* Returns the attribute name on the delegated relationship if $name is
* delegated or null if not delegated.
*
* @param string $name Name of an attribute
* @param DelegateOptions $delegate An array containing delegate data
*/
private function is_delegated(string $name, array $delegate): ?string
{
if (is_array($delegate)) {
if (!empty($delegate['prefix'])) {
$name = substr($name, strlen($delegate['prefix']) + 1);
}
if (in_array($name, $delegate['delegate'])) {
return $name;
}
}
return null;
}
/**
* Determine if the model is in read-only mode.
*/
public function is_readonly(): bool
{
return $this->__readonly;
}
/**
* Determine if the model is a new record.
*/
public function is_new_record(): bool
{
return $this->__new_record;
}
/**
* Throws an exception if this model is set to readonly.
*
* @param string $method_name Name of method that was invoked on model for exception message
*
* @throws ReadOnlyException
*/
private function verify_not_readonly(string $method_name): void
{
if ($this->is_readonly()) {
throw new ReadOnlyException(get_class($this), $method_name);
}
}
/**
* Retrieve the connection for this model.
*
* @return Connection
*/
public static function connection()
{
return static::table()->conn;
}
/**
* Re-establishes the database connection with a new connection.
*
* @return Connection
*/
public static function reestablish_connection()
{
return static::table()->reestablish_connection();
}
/**
* Returns the {@link Table} object for this model.
*
* Be sure to call in static scoping: static::table()
*
* @return Table
*/
protected static function table()
{
$table = Table::load(get_called_class());
return $table;
}
/**
* Creates a model and saves it to the database.
*
* @param Attributes $attributes Array of the models attributes
* @param bool $validate True if the validators should be run
* @param bool $guard_attributes Set to true to guard protected/non-accessible attributes
*/
public static function create(array $attributes, bool $validate = true, bool $guard_attributes = true): static
{
$class_name = get_called_class();
$model = new $class_name($attributes, $guard_attributes);
$model->save($validate);
return $model;
}
/**
* Save the model to the database.
*
* This function will automatically determine if an INSERT or UPDATE needs to occur.
* If a validation or a callback for this model returns false, then the model will
* not be saved and this will return false.
*
* If saving an existing model only data that has changed will be saved.
*
* @param bool $validate Set to true or false depending on if you want the validators to run or not
*
* @return bool True if the model was saved to the database otherwise false
*/
public function save($validate = true)
{
$this->verify_not_readonly('save');
return $this->is_new_record() ? $this->insert($validate) : $this->update($validate);
}
/**
* Issue an INSERT sql statement for this model's attribute.
*
* @see save
*
* @param bool $validate Set to true or false depending on if you want the validators to run or not
*
* @return bool True if the model was saved to the database otherwise false
*/
private function insert($validate = true)
{
$this->verify_not_readonly('insert');
if ($validate && !$this->_validate() || !$this->invoke_callback('before_create', false)) {
return false;
}
$table = static::table();
if (!($attributes = $this->dirty_attributes())) {
$attributes = $this->attributes;
}
$pk = $this->get_primary_key();
$use_sequence = false;
if (!empty($table->sequence) && !isset($attributes[$pk])) {
// unset pk that was set to null
if (array_key_exists($pk, $attributes)) {
unset($attributes[$pk]);
}
$table->insert($attributes, $pk, $table->sequence);
$use_sequence = true;
} else {
$table->insert($attributes);
}
$pk = strtolower($pk);
$column = $table->get_column_by_inflected_name($pk);
if (isset($column) && ($column->auto_increment || $use_sequence)) {
$this->attributes[$pk] = $column->cast(static::connection()->insert_id($table->sequence ?? null), static::connection());
}
$this->__new_record = false;