@@ -64,13 +64,36 @@ class Entity
6464 'casts ' => []
6565 ];
6666
67+ /**
68+ * Holds original copies of all class vars so
69+ * we can determine what's actually been changed
70+ * and not accidentally write nulls where we shouldn't.
71+ *
72+ * @var array
73+ */
74+ protected $ _original = [];
75+
6776 /**
6877 * Allows filling in Entity parameters during construction.
6978 *
7079 * @param array|null $data
7180 */
7281 public function __construct (array $ data = null )
7382 {
83+ // Collect any original values of things
84+ // so we can compare later to see what's changed
85+ $ properties = get_object_vars ($ this );
86+
87+ foreach ($ properties as $ key => $ value )
88+ {
89+ if (substr ($ key , 0 , 1 ) == '_ ' )
90+ {
91+ unset($ properties [$ key ]);
92+ }
93+ }
94+
95+ $ this ->_original = $ properties ;
96+
7497 if (is_array ($ data ))
7598 {
7699 $ this ->fill ($ data );
@@ -108,8 +131,12 @@ public function fill(array $data)
108131 * values of this entity as an array. All values are accessed
109132 * through the __get() magic method so will have any casts, etc
110133 * applied to them.
134+ *
135+ * @param bool $onlyChanged If true, only return values that have changed since object creation
136+ *
137+ * @return array
111138 */
112- public function toArray (): array
139+ public function toArray (bool $ onlyChanged = false ): array
113140 {
114141 $ return = [];
115142
@@ -119,7 +146,12 @@ public function toArray(): array
119146
120147 foreach ($ properties as $ key => $ value )
121148 {
122- if ($ key == '_options ' ) continue ;
149+ if (substr ($ key , 0 , 1 ) == '_ ' ) continue ;
150+
151+ if ($ onlyChanged && $ this ->_original [$ key ] === null && $ value === null )
152+ {
153+ continue ;
154+ }
123155
124156 $ return [$ key ] = $ this ->__get ($ key );
125157 }
@@ -368,7 +400,7 @@ protected function mutateDate($value)
368400 *
369401 * @return mixed
370402 */
371-
403+
372404 protected function castAs ($ value , string $ type )
373405 {
374406 switch ($ type )
@@ -422,7 +454,7 @@ protected function castAs($value, string $type)
422454 * Cast as JSON
423455 *
424456 * @param mixed $value
425- * @param bool $asArray
457+ * @param bool $asArray
426458 *
427459 * @return mixed
428460 */
0 commit comments