diff --git a/src/Concerns/SerializesModels.php b/src/Concerns/SerializesModels.php index 002c6ba..b2fde53 100644 --- a/src/Concerns/SerializesModels.php +++ b/src/Concerns/SerializesModels.php @@ -8,16 +8,50 @@ trait SerializesModels { use BaseSerializesModels { __sleep as protected sleepFromBaseSerializesModels; + __wakeup as protected wakeupFromBaseSerializesModels; + __serialize as protected serializeFromBaseSerializesModels; + __unserialize as protected unserializeFromBaseSerializesModels; } public function __sleep() { $properties = $this->sleepFromBaseSerializesModels(); + array_walk($this->attributes, function (&$value) { + $value = $this->getSerializedPropertyValue($value); + }); + return array_values(array_diff($properties, [ 'request', 'runningAs', 'actingAs', 'errorBag', 'validator', 'commandInstance', 'commandSignature', 'commandDescription', 'getAttributesFromConstructor', ])); } + + public function __wakeup() + { + $this->wakeupFromBaseSerializesModels(); + + array_walk($this->attributes, function (&$value) { + $value = $this->getRestoredPropertyValue($value); + }); + } + + public function __serialize() + { + array_walk($this->attributes, function (&$value) { + $value = $this->getSerializedPropertyValue($value); + }); + + return $this->serializeFromBaseSerializesModels(); + } + + public function __unserialize(array $values) + { + $this->unserializeFromBaseSerializesModels($values); + + array_walk($this->attributes, function (&$value) { + $value = $this->getRestoredPropertyValue($value); + }); + } } diff --git a/tests/SerializesModelsTest.php b/tests/SerializesModelsTest.php new file mode 100644 index 0000000..4bf9e35 --- /dev/null +++ b/tests/SerializesModelsTest.php @@ -0,0 +1,56 @@ +loadLaravelMigrations(); + } + + /** @test */ + public function it_serializes_models_within_action_attributes() + { + $user = $this->createUser([ + 'name' => 'Action San', + ]); + + $action = new UpdateProfileDetails(['user' => $user, 'name' => 'Laravel San']); + + $this->assertNotFalse( + strpos(serialize($action), serialize($this->getSerializedPropertyValue($user))) + ); + } + + /** @test */ + public function it_unserializes_models_within_action_attributes() + { + $user = $this->createUser([ + 'name' => 'Action San', + ]); + + // We want to be sure we have fetched the user from the DB + // rather than straight up unserializing into the class. + $hasBeenRetrieved = false; + User::retrieved(function () use (&$hasBeenRetrieved) { + $hasBeenRetrieved = true; + }); + + $action = new UpdateProfileDetails(['user' => $user, 'name' => 'Laravel San']); + $rehydratedAction = unserialize(serialize($action)); + + $this->assertTrue( + $user->is($rehydratedAction->get('user')) + ); + $this->assertTrue($hasBeenRetrieved); + } +} \ No newline at end of file