-
Notifications
You must be signed in to change notification settings - Fork 11.1k
/
HasAttributes.php
2129 lines (1857 loc) · 60.4 KB
/
HasAttributes.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 Illuminate\Database\Eloquent\Concerns;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use DateTimeInterface;
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Casts\AsCollection;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\InvalidCastException;
use Illuminate\Database\Eloquent\JsonEncodingException;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\LazyLoadingViolationException;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use InvalidArgumentException;
use LogicException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
trait HasAttributes
{
/**
* The model's attributes.
*
* @var array
*/
protected $attributes = [];
/**
* The model attribute's original state.
*
* @var array
*/
protected $original = [];
/**
* The changed model attributes.
*
* @var array
*/
protected $changes = [];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [];
/**
* The attributes that have been cast using custom classes.
*
* @var array
*/
protected $classCastCache = [];
/**
* The attributes that have been cast using "Attribute" return type mutators.
*
* @var array
*/
protected $attributeCastCache = [];
/**
* The built-in, primitive cast types supported by Eloquent.
*
* @var string[]
*/
protected static $primitiveCastTypes = [
'array',
'bool',
'boolean',
'collection',
'custom_datetime',
'date',
'datetime',
'decimal',
'double',
'encrypted',
'encrypted:array',
'encrypted:collection',
'encrypted:json',
'encrypted:object',
'float',
'immutable_date',
'immutable_datetime',
'immutable_custom_datetime',
'int',
'integer',
'json',
'object',
'real',
'string',
'timestamp',
];
/**
* The attributes that should be mutated to dates.
*
* @deprecated Use the "casts" property
*
* @var array
*/
protected $dates = [];
/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat;
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [];
/**
* Indicates whether attributes are snake cased on arrays.
*
* @var bool
*/
public static $snakeAttributes = true;
/**
* The cache of the mutated attributes for each class.
*
* @var array
*/
protected static $mutatorCache = [];
/**
* The cache of the "Attribute" return type marked mutated attributes for each class.
*
* @var array
*/
protected static $attributeMutatorCache = [];
/**
* The cache of the "Attribute" return type marked mutated, gettable attributes for each class.
*
* @var array
*/
protected static $getAttributeMutatorCache = [];
/**
* The cache of the "Attribute" return type marked mutated, settable attributes for each class.
*
* @var array
*/
protected static $setAttributeMutatorCache = [];
/**
* The encrypter instance that is used to encrypt attributes.
*
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
public static $encrypter;
/**
* Convert the model's attributes to an array.
*
* @return array
*/
public function attributesToArray()
{
// If an attribute is a date, we will cast it to a string after converting it
// to a DateTime / Carbon instance. This is so we will get some consistent
// formatting while accessing attributes vs. arraying / JSONing a model.
$attributes = $this->addDateAttributesToArray(
$attributes = $this->getArrayableAttributes()
);
$attributes = $this->addMutatedAttributesToArray(
$attributes, $mutatedAttributes = $this->getMutatedAttributes()
);
// Next we will handle any casts that have been setup for this model and cast
// the values to their appropriate type. If the attribute has a mutator we
// will not perform the cast on those attributes to avoid any confusion.
$attributes = $this->addCastAttributesToArray(
$attributes, $mutatedAttributes
);
// Here we will grab all of the appended, calculated attributes to this model
// as these attributes are not really in the attributes array, but are run
// when we need to array or JSON the model for convenience to the coder.
foreach ($this->getArrayableAppends() as $key) {
$attributes[$key] = $this->mutateAttributeForArray($key, null);
}
return $attributes;
}
/**
* Add the date attributes to the attributes array.
*
* @param array $attributes
* @return array
*/
protected function addDateAttributesToArray(array $attributes)
{
foreach ($this->getDates() as $key) {
if (! isset($attributes[$key])) {
continue;
}
$attributes[$key] = $this->serializeDate(
$this->asDateTime($attributes[$key])
);
}
return $attributes;
}
/**
* Add the mutated attributes to the attributes array.
*
* @param array $attributes
* @param array $mutatedAttributes
* @return array
*/
protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes)
{
foreach ($mutatedAttributes as $key) {
// We want to spin through all the mutated attributes for this model and call
// the mutator for the attribute. We cache off every mutated attributes so
// we don't have to constantly check on attributes that actually change.
if (! array_key_exists($key, $attributes)) {
continue;
}
// Next, we will call the mutator for this attribute so that we can get these
// mutated attribute's actual values. After we finish mutating each of the
// attributes we will return this final array of the mutated attributes.
$attributes[$key] = $this->mutateAttributeForArray(
$key, $attributes[$key]
);
}
return $attributes;
}
/**
* Add the casted attributes to the attributes array.
*
* @param array $attributes
* @param array $mutatedAttributes
* @return array
*/
protected function addCastAttributesToArray(array $attributes, array $mutatedAttributes)
{
foreach ($this->getCasts() as $key => $value) {
if (! array_key_exists($key, $attributes) ||
in_array($key, $mutatedAttributes)) {
continue;
}
// Here we will cast the attribute. Then, if the cast is a date or datetime cast
// then we will serialize the date for the array. This will convert the dates
// to strings based on the date format specified for these Eloquent models.
$attributes[$key] = $this->castAttribute(
$key, $attributes[$key]
);
// If the attribute cast was a date or a datetime, we will serialize the date as
// a string. This allows the developers to customize how dates are serialized
// into an array without affecting how they are persisted into the storage.
if ($attributes[$key] && in_array($value, ['date', 'datetime', 'immutable_date', 'immutable_datetime'])) {
$attributes[$key] = $this->serializeDate($attributes[$key]);
}
if ($attributes[$key] && ($this->isCustomDateTimeCast($value) ||
$this->isImmutableCustomDateTimeCast($value))) {
$attributes[$key] = $attributes[$key]->format(explode(':', $value, 2)[1]);
}
if ($attributes[$key] && $attributes[$key] instanceof DateTimeInterface &&
$this->isClassCastable($key)) {
$attributes[$key] = $this->serializeDate($attributes[$key]);
}
if ($attributes[$key] && $this->isClassSerializable($key)) {
$attributes[$key] = $this->serializeClassCastableAttribute($key, $attributes[$key]);
}
if ($this->isEnumCastable($key) && (! ($attributes[$key] ?? null) instanceof Arrayable)) {
$attributes[$key] = isset($attributes[$key]) ? $attributes[$key]->value : null;
}
if ($attributes[$key] instanceof Arrayable) {
$attributes[$key] = $attributes[$key]->toArray();
}
}
return $attributes;
}
/**
* Get an attribute array of all arrayable attributes.
*
* @return array
*/
protected function getArrayableAttributes()
{
return $this->getArrayableItems($this->getAttributes());
}
/**
* Get all of the appendable values that are arrayable.
*
* @return array
*/
protected function getArrayableAppends()
{
if (! count($this->appends)) {
return [];
}
return $this->getArrayableItems(
array_combine($this->appends, $this->appends)
);
}
/**
* Get the model's relationships in array form.
*
* @return array
*/
public function relationsToArray()
{
$attributes = [];
foreach ($this->getArrayableRelations() as $key => $value) {
// If the values implements the Arrayable interface we can just call this
// toArray method on the instances which will convert both models and
// collections to their proper array form and we'll set the values.
if ($value instanceof Arrayable) {
$relation = $value->toArray();
}
// If the value is null, we'll still go ahead and set it in this list of
// attributes since null is used to represent empty relationships if
// if it a has one or belongs to type relationships on the models.
elseif (is_null($value)) {
$relation = $value;
}
// If the relationships snake-casing is enabled, we will snake case this
// key so that the relation attribute is snake cased in this returned
// array to the developers, making this consistent with attributes.
if (static::$snakeAttributes) {
$key = Str::snake($key);
}
// If the relation value has been set, we will set it on this attributes
// list for returning. If it was not arrayable or null, we'll not set
// the value on the array because it is some type of invalid value.
if (isset($relation) || is_null($value)) {
$attributes[$key] = $relation;
}
unset($relation);
}
return $attributes;
}
/**
* Get an attribute array of all arrayable relations.
*
* @return array
*/
protected function getArrayableRelations()
{
return $this->getArrayableItems($this->relations);
}
/**
* Get an attribute array of all arrayable values.
*
* @param array $values
* @return array
*/
protected function getArrayableItems(array $values)
{
if (count($this->getVisible()) > 0) {
$values = array_intersect_key($values, array_flip($this->getVisible()));
}
if (count($this->getHidden()) > 0) {
$values = array_diff_key($values, array_flip($this->getHidden()));
}
return $values;
}
/**
* Get an attribute from the model.
*
* @param string $key
* @return mixed
*/
public function getAttribute($key)
{
if (! $key) {
return;
}
// If the attribute exists in the attribute array or has a "get" mutator we will
// get the attribute's value. Otherwise, we will proceed as if the developers
// are asking for a relationship's value. This covers both types of values.
if (array_key_exists($key, $this->attributes) ||
array_key_exists($key, $this->casts) ||
$this->hasGetMutator($key) ||
$this->hasAttributeMutator($key) ||
$this->isClassCastable($key)) {
return $this->getAttributeValue($key);
}
// Here we will determine if the model base class itself contains this given key
// since we don't want to treat any of those methods as relationships because
// they are all intended as helper methods and none of these are relations.
if (method_exists(self::class, $key)) {
return;
}
return $this->getRelationValue($key);
}
/**
* Get a plain attribute (not a relationship).
*
* @param string $key
* @return mixed
*/
public function getAttributeValue($key)
{
return $this->transformModelValue($key, $this->getAttributeFromArray($key));
}
/**
* Get an attribute from the $attributes array.
*
* @param string $key
* @return mixed
*/
protected function getAttributeFromArray($key)
{
return $this->getAttributes()[$key] ?? null;
}
/**
* Get a relationship.
*
* @param string $key
* @return mixed
*/
public function getRelationValue($key)
{
// If the key already exists in the relationships array, it just means the
// relationship has already been loaded, so we'll just return it out of
// here because there is no need to query within the relations twice.
if ($this->relationLoaded($key)) {
return $this->relations[$key];
}
if (! $this->isRelation($key)) {
return;
}
if ($this->preventsLazyLoading) {
$this->handleLazyLoadingViolation($key);
}
// If the "attribute" exists as a method on the model, we will just assume
// it is a relationship and will load and return results from the query
// and hydrate the relationship's value on the "relationships" array.
return $this->getRelationshipFromMethod($key);
}
/**
* Determine if the given key is a relationship method on the model.
*
* @param string $key
* @return bool
*/
public function isRelation($key)
{
if ($this->hasAttributeMutator($key)) {
return false;
}
return method_exists($this, $key) ||
(static::$relationResolvers[get_class($this)][$key] ?? null);
}
/**
* Handle a lazy loading violation.
*
* @param string $key
* @return mixed
*/
protected function handleLazyLoadingViolation($key)
{
if (isset(static::$lazyLoadingViolationCallback)) {
return call_user_func(static::$lazyLoadingViolationCallback, $this, $key);
}
if (! $this->exists || $this->wasRecentlyCreated) {
return;
}
throw new LazyLoadingViolationException($this, $key);
}
/**
* Get a relationship value from a method.
*
* @param string $method
* @return mixed
*
* @throws \LogicException
*/
protected function getRelationshipFromMethod($method)
{
$relation = $this->$method();
if (! $relation instanceof Relation) {
if (is_null($relation)) {
throw new LogicException(sprintf(
'%s::%s must return a relationship instance, but "null" was returned. Was the "return" keyword used?', static::class, $method
));
}
throw new LogicException(sprintf(
'%s::%s must return a relationship instance.', static::class, $method
));
}
return tap($relation->getResults(), function ($results) use ($method) {
$this->setRelation($method, $results);
});
}
/**
* Determine if a get mutator exists for an attribute.
*
* @param string $key
* @return bool
*/
public function hasGetMutator($key)
{
return method_exists($this, 'get'.Str::studly($key).'Attribute');
}
/**
* Determine if a "Attribute" return type marked mutator exists for an attribute.
*
* @param string $key
* @return bool
*/
public function hasAttributeMutator($key)
{
if (isset(static::$attributeMutatorCache[get_class($this)][$key])) {
return static::$attributeMutatorCache[get_class($this)][$key];
}
if (! method_exists($this, $method = Str::camel($key))) {
return static::$attributeMutatorCache[get_class($this)][$key] = false;
}
$returnType = (new ReflectionMethod($this, $method))->getReturnType();
return static::$attributeMutatorCache[get_class($this)][$key] = $returnType &&
$returnType instanceof ReflectionNamedType &&
$returnType->getName() === Attribute::class;
}
/**
* Determine if a "Attribute" return type marked get mutator exists for an attribute.
*
* @param string $key
* @return bool
*/
public function hasAttributeGetMutator($key)
{
if (isset(static::$getAttributeMutatorCache[get_class($this)][$key])) {
return static::$getAttributeMutatorCache[get_class($this)][$key];
}
if (! $this->hasAttributeMutator($key)) {
return static::$getAttributeMutatorCache[get_class($this)][$key] = false;
}
return static::$getAttributeMutatorCache[get_class($this)][$key] = is_callable($this->{Str::camel($key)}()->get);
}
/**
* Get the value of an attribute using its mutator.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function mutateAttribute($key, $value)
{
return $this->{'get'.Str::studly($key).'Attribute'}($value);
}
/**
* Get the value of an "Attribute" return type marked attribute using its mutator.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function mutateAttributeMarkedAttribute($key, $value)
{
if (isset($this->attributeCastCache[$key])) {
return $this->attributeCastCache[$key];
}
$attribute = $this->{Str::camel($key)}();
$value = call_user_func($attribute->get ?: function ($value) {
return $value;
}, $value, $this->attributes);
if (! is_object($value) || ! $attribute->withObjectCaching) {
unset($this->attributeCastCache[$key]);
} else {
$this->attributeCastCache[$key] = $value;
}
return $value;
}
/**
* Get the value of an attribute using its mutator for array conversion.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function mutateAttributeForArray($key, $value)
{
if ($this->isClassCastable($key)) {
$value = $this->getClassCastableAttributeValue($key, $value);
} elseif (isset(static::$getAttributeMutatorCache[get_class($this)][$key]) &&
static::$getAttributeMutatorCache[get_class($this)][$key] === true) {
$value = $this->mutateAttributeMarkedAttribute($key, $value);
$value = $value instanceof DateTimeInterface
? $this->serializeDate($value)
: $value;
} else {
$value = $this->mutateAttribute($key, $value);
}
return $value instanceof Arrayable ? $value->toArray() : $value;
}
/**
* Merge new casts with existing casts on the model.
*
* @param array $casts
* @return $this
*/
public function mergeCasts($casts)
{
$this->casts = array_merge($this->casts, $casts);
return $this;
}
/**
* Cast an attribute to a native PHP type.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function castAttribute($key, $value)
{
$castType = $this->getCastType($key);
if (is_null($value) && in_array($castType, static::$primitiveCastTypes)) {
return $value;
}
// If the key is one of the encrypted castable types, we'll first decrypt
// the value and update the cast type so we may leverage the following
// logic for casting this value to any additionally specified types.
if ($this->isEncryptedCastable($key)) {
$value = $this->fromEncryptedString($value);
$castType = Str::after($castType, 'encrypted:');
}
switch ($castType) {
case 'int':
case 'integer':
return (int) $value;
case 'real':
case 'float':
case 'double':
return $this->fromFloat($value);
case 'decimal':
return $this->asDecimal($value, explode(':', $this->getCasts()[$key], 2)[1]);
case 'string':
return (string) $value;
case 'bool':
case 'boolean':
return (bool) $value;
case 'object':
return $this->fromJson($value, true);
case 'array':
case 'json':
return $this->fromJson($value);
case 'collection':
return new BaseCollection($this->fromJson($value));
case 'date':
return $this->asDate($value);
case 'datetime':
case 'custom_datetime':
return $this->asDateTime($value);
case 'immutable_date':
return $this->asDate($value)->toImmutable();
case 'immutable_custom_datetime':
case 'immutable_datetime':
return $this->asDateTime($value)->toImmutable();
case 'timestamp':
return $this->asTimestamp($value);
}
if ($this->isEnumCastable($key)) {
return $this->getEnumCastableAttributeValue($key, $value);
}
if ($this->isClassCastable($key)) {
return $this->getClassCastableAttributeValue($key, $value);
}
return $value;
}
/**
* Cast the given attribute using a custom cast class.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function getClassCastableAttributeValue($key, $value)
{
if (isset($this->classCastCache[$key])) {
return $this->classCastCache[$key];
} else {
$caster = $this->resolveCasterClass($key);
$value = $caster instanceof CastsInboundAttributes
? $value
: $caster->get($this, $key, $value, $this->attributes);
if ($caster instanceof CastsInboundAttributes || ! is_object($value)) {
unset($this->classCastCache[$key]);
} else {
$this->classCastCache[$key] = $value;
}
return $value;
}
}
/**
* Cast the given attribute to an enum.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function getEnumCastableAttributeValue($key, $value)
{
if (is_null($value)) {
return;
}
$castType = $this->getCasts()[$key];
if ($value instanceof $castType) {
return $value;
}
return $castType::from($value);
}
/**
* Get the type of cast for a model attribute.
*
* @param string $key
* @return string
*/
protected function getCastType($key)
{
if ($this->isCustomDateTimeCast($this->getCasts()[$key])) {
return 'custom_datetime';
}
if ($this->isImmutableCustomDateTimeCast($this->getCasts()[$key])) {
return 'immutable_custom_datetime';
}
if ($this->isDecimalCast($this->getCasts()[$key])) {
return 'decimal';
}
return trim(strtolower($this->getCasts()[$key]));
}
/**
* Increment or decrement the given attribute using the custom cast class.
*
* @param string $method
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function deviateClassCastableAttribute($method, $key, $value)
{
return $this->resolveCasterClass($key)->{$method}(
$this, $key, $value, $this->attributes
);
}
/**
* Serialize the given attribute using the custom cast class.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function serializeClassCastableAttribute($key, $value)
{
return $this->resolveCasterClass($key)->serialize(
$this, $key, $value, $this->attributes
);
}
/**
* Determine if the cast type is a custom date time cast.
*
* @param string $cast
* @return bool
*/
protected function isCustomDateTimeCast($cast)
{
return strncmp($cast, 'date:', 5) === 0 ||
strncmp($cast, 'datetime:', 9) === 0;
}
/**
* Determine if the cast type is an immutable custom date time cast.
*
* @param string $cast
* @return bool
*/
protected function isImmutableCustomDateTimeCast($cast)
{
return strncmp($cast, 'immutable_date:', 15) === 0 ||
strncmp($cast, 'immutable_datetime:', 19) === 0;
}
/**
* Determine if the cast type is a decimal cast.
*
* @param string $cast
* @return bool
*/
protected function isDecimalCast($cast)
{
return strncmp($cast, 'decimal:', 8) === 0;
}
/**
* Set a given attribute on the model.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
public function setAttribute($key, $value)
{
// First we will check for the presence of a mutator for the set operation
// which simply lets the developers tweak the attribute as it is set on
// this model, such as "json_encoding" a listing of data for storage.
if ($this->hasSetMutator($key)) {
return $this->setMutatedAttributeValue($key, $value);
} elseif ($this->hasAttributeSetMutator($key)) {
return $this->setAttributeMarkedMutatedAttributeValue($key, $value);
}
// If an attribute is listed as a "date", we'll convert it from a DateTime
// instance into a form proper for storage on the database tables using
// the connection grammar's date format. We will auto set the values.
elseif ($value && $this->isDateAttribute($key)) {
$value = $this->fromDateTime($value);
}
if ($this->isEnumCastable($key)) {
$this->setEnumCastableAttribute($key, $value);
return $this;
}
if ($this->isClassCastable($key)) {
$this->setClassCastableAttribute($key, $value);
return $this;
}
if (! is_null($value) && $this->isJsonCastable($key)) {
$value = $this->castAttributeAsJson($key, $value);
}
// If this attribute contains a JSON ->, we'll set the proper value in the
// attribute's underlying array. This takes care of properly nesting an
// attribute in the array's value in the case of deeply nested items.
if (Str::contains($key, '->')) {
return $this->fillJsonAttribute($key, $value);
}
if (! is_null($value) && $this->isEncryptedCastable($key)) {
$value = $this->castAttributeAsEncryptedString($key, $value);
}
$this->attributes[$key] = $value;
return $this;
}
/**
* Determine if a set mutator exists for an attribute.
*
* @param string $key
* @return bool
*/
public function hasSetMutator($key)
{
return method_exists($this, 'set'.Str::studly($key).'Attribute');
}
/**
* Determine if an "Attribute" return type marked set mutator exists for an attribute.
*
* @param string $key
* @return bool
*/
public function hasAttributeSetMutator($key)
{
$class = get_class($this);
if (isset(static::$setAttributeMutatorCache[$class][$key])) {
return static::$setAttributeMutatorCache[$class][$key];
}
if (! method_exists($this, $method = Str::camel($key))) {
return static::$setAttributeMutatorCache[$class][$key] = false;
}
$returnType = (new ReflectionMethod($this, $method))->getReturnType();
return static::$setAttributeMutatorCache[$class][$key] = $returnType &&
$returnType instanceof ReflectionNamedType &&
$returnType->getName() === Attribute::class &&
is_callable($this->{$method}()->set);
}
/**
* Set the value of an attribute using its mutator.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function setMutatedAttributeValue($key, $value)
{
return $this->{'set'.Str::studly($key).'Attribute'}($value);