@@ -134,25 +134,24 @@ public function eraseCredentials()
134134
135135 /**
136136 * {@inheritdoc}
137+ *
138+ * @param bool $isCalledFromOverridingMethod Must be set to true when called from an overriding method
139+ *
140+ * @return string|array Returns an array when $isCalledFromOverridingMethod is set to true
137141 */
138142 public function serialize ()
139143 {
140- return serialize (
141- [
142- \is_object ($ this ->user ) ? clone $ this ->user : $ this ->user ,
143- $ this ->authenticated ,
144- array_map (function ($ role ) { return clone $ role ; }, $ this ->roles ),
145- $ this ->attributes ,
146- ]
147- );
144+ $ serialized = [$ this ->user , $ this ->authenticated , $ this ->roles , $ this ->attributes ];
145+
146+ return $ this ->doSerialize ($ serialized , \func_num_args () ? \func_get_arg (0 ) : null );
148147 }
149148
150149 /**
151150 * {@inheritdoc}
152151 */
153152 public function unserialize ($ serialized )
154153 {
155- list ($ this ->user , $ this ->authenticated , $ this ->roles , $ this ->attributes ) = unserialize ($ serialized );
154+ list ($ this ->user , $ this ->authenticated , $ this ->roles , $ this ->attributes ) = \is_array ( $ serialized ) ? $ serialized : unserialize ($ serialized );
156155 }
157156
158157 /**
@@ -232,6 +231,19 @@ public function __toString()
232231 return sprintf ('%s(user="%s", authenticated=%s, roles="%s") ' , $ class , $ this ->getUsername (), json_encode ($ this ->authenticated ), implode (', ' , $ roles ));
233232 }
234233
234+ /**
235+ * @internal
236+ */
237+ protected function doSerialize ($ serialized , $ isCalledFromOverridingMethod )
238+ {
239+ if (null === $ isCalledFromOverridingMethod ) {
240+ $ trace = debug_backtrace (DEBUG_BACKTRACE_PROVIDE_OBJECT , 3 );
241+ $ isCalledFromOverridingMethod = isset ($ trace [2 ]['function ' ], $ trace [2 ]['object ' ]) && 'serialize ' === $ trace [2 ]['function ' ] && $ this === $ trace [2 ]['object ' ];
242+ }
243+
244+ return $ isCalledFromOverridingMethod ? $ serialized : serialize ($ serialized );
245+ }
246+
235247 private function hasUserChanged (UserInterface $ user )
236248 {
237249 if (!($ this ->user instanceof UserInterface)) {
0 commit comments