@@ -127,7 +127,7 @@ class Entity implements JsonSerializable
127127 /**
128128 * The data caster.
129129 */
130- protected DataCaster $ dataCaster ;
130+ protected ? DataCaster $ dataCaster = null ;
131131
132132 /**
133133 * Holds info whenever properties have to be casted.
@@ -146,12 +146,7 @@ class Entity implements JsonSerializable
146146 */
147147 public function __construct (?array $ data = null )
148148 {
149- $ this ->dataCaster = new DataCaster (
150- array_merge ($ this ->defaultCastHandlers , $ this ->castHandlers ),
151- null ,
152- null ,
153- false ,
154- );
149+ $ this ->dataCaster = $ this ->dataCaster ();
155150
156151 $ this ->syncOriginal ();
157152
@@ -568,10 +563,37 @@ protected function mutateDate($value)
568563 */
569564 protected function castAs ($ value , string $ attribute , string $ method = 'get ' )
570565 {
571- return $ this ->dataCaster
572- // @TODO if $casts is readonly, we don't need the setTypes() method.
573- ->setTypes ($ this ->casts )
574- ->castAs ($ value , $ attribute , $ method );
566+ if ($ this ->dataCaster () instanceof DataCaster) {
567+ return $ this ->dataCaster
568+ // @TODO if $casts is readonly, we don't need the setTypes() method.
569+ ->setTypes ($ this ->casts )
570+ ->castAs ($ value , $ attribute , $ method );
571+ }
572+
573+ return $ value ;
574+ }
575+
576+ /**
577+ * This method allows you to refuse to contain an unnecessary DataCaster if you do not use casting.
578+ */
579+ protected function dataCaster (): ?DataCaster
580+ {
581+ if (! $ this ->_cast ) {
582+ $ this ->dataCaster = null ;
583+
584+ return null ;
585+ }
586+
587+ if (! $ this ->dataCaster instanceof DataCaster) {
588+ $ this ->dataCaster = new DataCaster (
589+ array_merge ($ this ->defaultCastHandlers , $ this ->castHandlers ),
590+ null ,
591+ null ,
592+ false ,
593+ );
594+ }
595+
596+ return $ this ->dataCaster ;
575597 }
576598
577599 /**
@@ -598,6 +620,9 @@ public function cast(?bool $cast = null)
598620
599621 $ this ->_cast = $ cast ;
600622
623+ // Synchronize option with DataCaster initialization
624+ $ this ->dataCaster ();
625+
601626 return $ this ;
602627 }
603628
0 commit comments