-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Model.php
1363 lines (1196 loc) · 38.1 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 namespace Winter\Storm\Database;
use Illuminate\Support\Facades\Cache;
use Closure;
use DateTimeInterface;
use Exception;
use Illuminate\Database\Eloquent\Collection as CollectionBase;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Throwable;
use Winter\Storm\Argon\Argon;
use Winter\Storm\Support\Arr;
use Winter\Storm\Support\Str;
/**
* Active Record base class.
*
* Extends Eloquent with added extendability and deferred bindings.
*
* @author Alexey Bobkov, Samuel Georges
*
* @method static mixed extend(callable $callback, bool $scoped = false, ?object $outerScope = null)
*/
class Model extends EloquentModel implements ModelInterface
{
use Concerns\GuardsAttributes;
use Concerns\HasRelationships;
use Concerns\HidesAttributes;
use Traits\Purgeable;
use \Winter\Storm\Support\Traits\Emitter;
use \Winter\Storm\Extension\ExtendableTrait {
addDynamicProperty as protected extendableAddDynamicProperty;
}
use \Winter\Storm\Database\Traits\DeferredBinding;
/**
* @var string|array|null Extensions implemented by this class.
*/
public $implement = null;
/**
* @var array<string, mixed> Make the model's attributes public so behaviors can modify them.
*/
public $attributes = [];
/**
* @var array List of attribute names which are json encoded and decoded from the database.
*/
protected $jsonable = [];
/**
* @var array List of datetime attributes to convert to an instance of Carbon/DateTime objects.
*/
protected $dates = [];
/**
* @var array List of attributes which should not be saved to the database.
*/
protected $purgeable = [];
/**
* @var bool Indicates if duplicate queries from this model should be cached in memory.
*/
public $duplicateCache = true;
/**
* @var bool Indicates if all string model attributes will be trimmed prior to saving.
*/
public $trimStringAttributes = true;
/**
* @var array The array of models booted events.
*/
protected static $eventsBooted = [];
/**
* Constructor
*/
public function __construct(array $attributes = [])
{
parent::__construct();
$this->bootNicerEvents();
$this->extendableConstruct();
$this->fill($attributes);
}
/**
* Static helper for isDatabaseReady()
*/
public static function hasDatabaseTable(): bool
{
return (new static)->isDatabaseReady();
}
/**
* Check if the model's database connection is ready
*/
public function isDatabaseReady(): bool
{
$cacheKey = sprintf('winter.storm::model.%s.isDatabaseReady.%s.%s', get_class($this), $this->getConnectionName() ?? '', $this->getTable());
if ($result = Cache::get($cacheKey)) {
return $result;
}
// Resolver hasn't been set yet
/** @phpstan-ignore-next-line */
if (!static::getConnectionResolver()) {
return false;
}
// Connection hasn't been set yet or the database doesn't exist
try {
$connection = $this->getConnection();
$connection->getPdo();
} catch (Throwable $ex) {
return false;
}
// Database exists but table doesn't
try {
$schema = $connection->getSchemaBuilder();
$table = $this->getTable();
if (!$schema->hasTable($table)) {
return false;
}
} catch (Throwable $ex) {
return false;
}
Cache::forever($cacheKey, true);
return true;
}
/**
* Create a new model and return the instance.
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|static
*/
public static function make($attributes = [])
{
return new static($attributes);
}
/**
* Save a new model and return the instance.
* @param array $attributes
* @param string $sessionKey
* @return \Illuminate\Database\Eloquent\Model|static
*/
public static function create(array $attributes = [], $sessionKey = null)
{
$model = new static($attributes);
$model->save([], $sessionKey);
return $model;
}
/**
* Reloads the model attributes from the database.
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function reload()
{
static::flushDuplicateCache();
if (!$this->exists) {
$this->syncOriginal();
}
elseif ($fresh = static::find($this->getKey())) {
$this->setRawAttributes($fresh->getAttributes(), true);
}
return $this;
}
/**
* Reloads the model relationship cache.
* @param string $relationName
* @return void
*/
public function reloadRelations($relationName = null)
{
static::flushDuplicateCache();
if (!$relationName) {
$this->setRelations([]);
}
else {
unset($this->relations[$relationName]);
}
}
/**
* Bind some nicer events to this model, in the format of method overrides.
*/
protected function bootNicerEvents()
{
$class = get_called_class();
// If the $dispatcher hasn't been set yet don't bother trying
// to register the nicer model events yet since it will silently fail
if (!isset(static::$dispatcher)) {
return;
}
// Events have already been booted, continue
if (isset(static::$eventsBooted[$class])) {
return;
}
$radicals = ['creat', 'sav', 'updat', 'delet', 'fetch'];
$hooks = ['before' => 'ing', 'after' => 'ed'];
foreach ($radicals as $radical) {
foreach ($hooks as $hook => $event) {
$eventMethod = $radical . $event; // saving / saved
$method = $hook . ucfirst($radical); // beforeSave / afterSave
if ($radical != 'fetch') {
$method .= 'e';
}
self::$eventMethod(function ($model) use ($method) {
if ($model->methodExists($method)) {
// Register the method as a listener with default priority
// to allow for complete control over the execution order
$model->bindEventOnce('model.' . $method, [$model, $method]);
}
// First listener that returns a non-null result will cancel the
// further propagation of the event; If that result is false, the
// underlying action will get cancelled (e.g. creating, saving, deleting)
return $model->fireEvent('model.' . $method, halt: true);
});
}
}
/*
* Hook to boot events
*/
static::registerModelEvent('booted', function ($model) {
/**
* @event model.afterBoot
* Called after the model is booted
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.afterBoot', function () use (\Winter\Storm\Database\Model $model) {
* \Log::info(get_class($model) . ' has booted');
* });
*
*/
$model->fireEvent('model.afterBoot');
if ($model->methodExists('afterBoot')) {
return $model->afterBoot();
}
});
static::$eventsBooted[$class] = true;
}
/**
* Remove all of the event listeners for the model
* Also flush registry of models that had events booted
* Allows painless unit testing.
*
* @override
* @return void
*/
public static function flushEventListeners()
{
parent::flushEventListeners();
static::$eventsBooted = [];
}
/**
* Handle the "creating" model event
*/
protected function beforeCreate()
{
/**
* @event model.beforeCreate
* Called before the model is created
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.beforeCreate', function () use (\Winter\Storm\Database\Model $model) {
* if (!$model->isValid()) {
* throw new \Exception("Invalid Model!");
* }
* });
*
*/
}
/**
* Handle the "created" model event
*/
protected function afterCreate()
{
/**
* @event model.afterCreate
* Called after the model is created
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.afterCreate', function () use (\Winter\Storm\Database\Model $model) {
* \Log::info("{$model->name} was created!");
* });
*
*/
}
/**
* Handle the "updating" model event
*/
protected function beforeUpdate()
{
/**
* @event model.beforeUpdate
* Called before the model is updated
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.beforeUpdate', function () use (\Winter\Storm\Database\Model $model) {
* if (!$model->isValid()) {
* throw new \Exception("Invalid Model!");
* }
* });
*
*/
}
/**
* Handle the "updated" model event
*/
protected function afterUpdate()
{
/**
* @event model.afterUpdate
* Called after the model is updated
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.afterUpdate', function () use (\Winter\Storm\Database\Model $model) {
* if ($model->title !== $model->original['title']) {
* \Log::info("{$model->name} updated its title!");
* }
* });
*
*/
}
/**
* Handle the "saving" model event
*/
protected function beforeSave()
{
/**
* @event model.beforeSave
* Called before the model is saved
* > **Note:** This is called both when creating and updating and is also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.beforeSave', function () use (\Winter\Storm\Database\Model $model) {
* if (!$model->isValid()) {
* throw new \Exception("Invalid Model!");
* }
* });
*
*/
}
/**
* Handle the "saved" model event
*/
protected function afterSave()
{
/**
* @event model.afterSave
* Called after the model is saved
* > **Note:** This is called both when creating and updating and is also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.afterSave', function () use (\Winter\Storm\Database\Model $model) {
* if ($model->title !== $model->original['title']) {
* \Log::info("{$model->name} updated its title!");
* }
* });
*
*/
}
/**
* Handle the "deleting" model event
*/
protected function beforeDelete()
{
/**
* @event model.beforeDelete
* Called before the model is deleted
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.beforeDelete', function () use (\Winter\Storm\Database\Model $model) {
* if (!$model->isAllowedToBeDeleted()) {
* throw new \Exception("You cannot delete me!");
* }
* });
*
*/
}
/**
* Handle the "deleted" model event
*/
protected function afterDelete()
{
/**
* @event model.afterDelete
* Called after the model is deleted
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.afterDelete', function () use (\Winter\Storm\Database\Model $model) {
* \Log::info("{$model->name} was deleted");
* });
*
*/
}
/**
* Handle the "fetching" model event
*/
protected function beforeFetch()
{
/**
* @event model.beforeFetch
* Called before the model is fetched
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.beforeFetch', function () use (\Winter\Storm\Database\Model $model) {
* if (!\Auth::getUser()->hasAccess('fetch.this.model')) {
* throw new \Exception("You shall not pass!");
* }
* });
*
*/
}
/**
* Handle the "fetched" model event
*/
protected function afterFetch()
{
/**
* @event model.afterFetch
* Called after the model is fetched
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.afterFetch', function () use (\Winter\Storm\Database\Model $model) {
* \Log::info("{$model->name} was retrieved from the database");
* });
*
*/
}
/**
* Flush the memory cache.
* @return void
*/
public static function flushDuplicateCache()
{
MemoryCache::instance()->flush();
}
/**
* Create a new model instance that is existing.
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function newFromBuilder($attributes = [], $connection = null)
{
$instance = $this->newInstance([], true);
if ($instance->fireModelEvent('fetching') === false) {
return $instance;
}
$instance->setRawAttributes((array) $attributes, true);
$instance->fireModelEvent('fetched', false);
$instance->setConnection($connection ?: $this->connection);
$instance->fireModelEvent('retrieved', false);
return $instance;
}
/**
* Create a new native event for handling beforeFetch().
* @param Closure|string $callback
* @return void
*/
public static function fetching($callback)
{
static::registerModelEvent('fetching', $callback);
}
/**
* Create a new native event for handling afterFetch().
* @param Closure|string $callback
* @return void
*/
public static function fetched($callback)
{
static::registerModelEvent('fetched', $callback);
}
/**
* Checks if an attribute is jsonable or not.
*
* @return bool
*/
public function isJsonable($key)
{
return in_array($key, $this->jsonable);
}
/**
* Get the jsonable attributes name
*
* @return array
*/
public function getJsonable()
{
return $this->jsonable;
}
/**
* Set the jsonable attributes for the model.
*
* @param array $jsonable
* @return $this
*/
public function jsonable(array $jsonable)
{
$this->jsonable = $jsonable;
return $this;
}
//
// Overrides
//
/**
* Get the observable event names.
* @return array
*/
public function getObservableEvents()
{
return array_merge(
[
'creating', 'created', 'updating', 'updated',
'deleting', 'deleted', 'saving', 'saved',
'restoring', 'restored', 'fetching', 'fetched'
],
$this->observables
);
}
/**
* Get a fresh timestamp for the model.
*
* @return \Illuminate\Support\Carbon
*/
public function freshTimestamp()
{
return new Argon;
}
/**
* Return a timestamp as DateTime object.
*
* @param mixed $value
* @return \Carbon\Carbon
*/
protected function asDateTime($value)
{
// If this value is already a Argon instance, we shall just return it as is.
// This prevents us having to re-instantiate a Argon instance when we know
// it already is one, which wouldn't be fulfilled by the DateTime check.
if ($value instanceof Argon) {
return $value;
}
// If the value is already a DateTime instance, we will just skip the rest of
// these checks since they will be a waste of time, and hinder performance
// when checking the field. We will just return the DateTime right away.
if ($value instanceof DateTimeInterface) {
return new Argon(
$value->format('Y-m-d H:i:s.u'),
$value->getTimezone()
);
}
// If this value is an integer, we will assume it is a UNIX timestamp's value
// and format a Carbon object from this timestamp. This allows flexibility
// when defining your date fields as they might be UNIX timestamps here.
if (is_numeric($value)) {
return Argon::createFromTimestamp($value);
}
// If the value is in simply year, month, day format, we will instantiate the
// Carbon instances from that format. Again, this provides for simple date
// fields on the database, while still supporting Carbonized conversion.
if ($this->isStandardDateFormat($value)) {
return Argon::createFromFormat('Y-m-d', $value)->startOfDay();
}
$format = $this->getDateFormat();
// https://bugs.php.net/bug.php?id=75577
if (version_compare(PHP_VERSION, '7.3.0-dev', '<')) {
$format = str_replace('.v', '.u', $format);
}
// If the value is expected to end in milli or micro seconds but doesn't
// then we should attempt to fix it as it's most likely from the datepicker
// which doesn't support sending micro or milliseconds
// @see https://github.com/rainlab/blog-plugin/issues/334
if (str_contains($format, '.') && !str_contains($value, '.')) {
if (ends_with($format, '.u')) {
$value .= '.000000';
}
if (ends_with($format, '.v')) {
$value .= '.000';
}
}
// Finally, we will just assume this date is in the format used by default on
// the database connection and use that format to create the Carbon object
// that is returned back out to the developers after we convert it here.
return Argon::createFromFormat($format, $value);
}
/**
* Convert a DateTime to a storable string.
*
* @param \DateTime|int|null $value
* @return string|null
*/
public function fromDateTime($value = null)
{
if (is_null($value)) {
return $value;
}
return parent::fromDateTime($value);
}
/**
* Create a new Eloquent query builder for the model.
*
* @param \Winter\Storm\Database\QueryBuilder $query
* @return \Winter\Storm\Database\Builder
*/
public function newEloquentBuilder($query)
{
return new Builder($query);
}
/**
* Get a new query builder instance for the connection.
*
* @return \Winter\Storm\Database\QueryBuilder
*/
protected function newBaseQueryBuilder()
{
$conn = $this->getConnection();
$grammar = $conn->getQueryGrammar();
$builder = new QueryBuilder($conn, $grammar, $conn->getPostProcessor());
if ($this->duplicateCache) {
$builder->enableDuplicateCache();
}
return $builder;
}
/**
* Create a new Model Collection instance.
*
* @param array $models
* @return \Winter\Storm\Database\Collection
*/
public function newCollection(array $models = [])
{
return new Collection($models);
}
//
// Magic
//
/**
* Programmatically adds a property to the extendable class
*
* @param string $dynamicName The name of the property to add
* @param mixed $value The value of the property
* @return void
*/
public function addDynamicProperty($dynamicName, $value = null)
{
if (array_key_exists($dynamicName, $this->getDynamicProperties())) {
return;
}
// Ensure that dynamic properties are automatically purged
$this->addPurgeable($dynamicName);
// Add the dynamic property
$this->extendableAddDynamicProperty($dynamicName, $value);
}
public function __get($name)
{
return $this->extendableGet($name);
}
public function __set($name, $value)
{
$this->extendableSet($name, $value);
}
public function __call($name, $params)
{
if ($name === 'extend') {
if (empty($params[0]) || !is_callable($params[0])) {
throw new \InvalidArgumentException('The extend() method requires a callback parameter or closure.');
}
if ($params[0] instanceof \Closure) {
return $params[0]->call($this, $params[1] ?? $this);
}
return \Closure::fromCallable($params[0])->call($this, $params[1] ?? $this);
}
/*
* Never call handleRelation() anywhere else as it could
* break getRelationCaller(), use $this->{$name}() instead
*/
if ($this->hasRelation($name, true)) {
return $this->handleRelation($name);
}
return $this->extendableCall($name, $params);
}
public static function __callStatic($name, $params)
{
if ($name === 'extend') {
if (empty($params[0])) {
throw new \InvalidArgumentException('The extend() method requires a callback parameter or closure.');
}
self::extendableExtendCallback($params[0], $params[1] ?? false, $params[2] ?? null);
return;
}
return parent::__callStatic($name, $params);
}
/**
* Determine if an attribute or relation exists on the model.
*
* @param string $key
* @return bool
*/
public function __isset($key)
{
return !is_null($this->getAttribute($key));
}
/**
* This a custom piece of logic specifically to satisfy Twig's
* desire to return a relation object instead of loading the
* related model.
*
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset): bool
{
if ($result = parent::offsetExists($offset)) {
return $result;
}
return $this->hasRelation($offset);
}
//
// Pivot
//
/**
* Create a generic pivot model instance.
* @param \Winter\Storm\Database\Model $parent
* @param array $attributes
* @param string $table
* @param bool $exists
* @param string|null $using
* @return \Winter\Storm\Database\Pivot
*/
public function newPivot(EloquentModel $parent, array $attributes, $table, $exists, $using = null)
{
return $using
? $using::fromRawAttributes($parent, $attributes, $table, $exists)
: Pivot::fromAttributes($parent, $attributes, $table, $exists);
}
/**
* Create a pivot model instance specific to a relation.
* @param \Winter\Storm\Database\Model $parent
* @param string $relationName
* @param array $attributes
* @param string $table
* @param bool $exists
* @return \Winter\Storm\Database\Pivot|null
*/
public function newRelationPivot($relationName, $parent, $attributes, $table, $exists)
{
$relation = $this->{$relationName}();
$pivotModel = $relation->getPivotClass();
return $pivotModel::fromRawAttributes($parent, $attributes, $table, $exists);
}
//
// Saving
//
/**
* Save the model to the database. Is used by {@link save()} and {@link forceSave()}.
* @param array $options
* @return bool
*/
protected function saveInternal(array $options = [])
{
/**
* @event model.saveInternal
* Called before the model is saved
* > **Note:** also triggered in Winter\Storm\Halcyon\Model
*
* Example usage:
*
* $model->bindEvent('model.saveInternal', function ((array) $attributes, (array) $options) use (\Winter\Storm\Database\Model $model) {
* // Prevent anything from saving ever!
* return false;
* });
*
*/
if ($this->fireEvent('model.saveInternal', [$this->attributes, $options], true) === false) {
return false;
}
/*
* Validate attributes before trying to save
*/
foreach ($this->attributes as $attribute => $value) {
if (is_array($value)) {
throw new Exception(sprintf('Unexpected type of array when attempting to save attribute "%s", try adding it to the $jsonable property.', $attribute));
}
}
// Apply pre deferred bindings
if ($this->sessionKey !== null) {
$this->commitDeferredBefore($this->sessionKey);
}
// Save the record
$result = parent::save($options);
// Halted by event
if ($result === false) {
return $result;
}
// Apply post deferred bindings
if ($this->sessionKey !== null) {
$this->commitDeferredAfter($this->sessionKey);
}
return $result;
}
/**
* Save the model to the database.
* @param array $options
* @param string|null $sessionKey
* @return bool
*/
public function save(?array $options = [], $sessionKey = null)
{
$this->sessionKey = $sessionKey;
return $this->saveInternal(['force' => false] + (array) $options);
}
/**
* Save the model and all of its relationships.
*
* @param array $options
* @param string|null $sessionKey
* @return bool
*/
public function push(?array $options = [], $sessionKey = null)
{
$always = Arr::get($options, 'always', false);
if (!$this->save([], $sessionKey) && !$always) {
return false;
}
foreach ($this->relations as $name => $models) {
if (!$this->isRelationPushable($name)) {
continue;
}
if ($models instanceof CollectionBase) {
$models = $models->all();
}
elseif ($models instanceof EloquentModel) {
$models = [$models];
}
else {
$models = (array) $models;
}
foreach (array_filter($models) as $model) {
if (!$model->push(null, $sessionKey)) {
return false;
}
}
}
return true;
}
/**
* Pushes the first level of relations even if the parent
* model has no changes.
*
* @param array $options
* @param string|null $sessionKey
* @return bool
*/
public function alwaysPush(?array $options = [], $sessionKey = null)
{
return $this->push(['always' => true] + (array) $options, $sessionKey);
}
//
// Deleting
//
/**
* Perform the actual delete query on this model instance.
* @return void
*/
protected function performDeleteOnModel()
{
$this->performDeleteOnRelations();
parent::performDeleteOnModel();
}
//
// Adders
//
/**
* Add attribute casts for the model.