Skip to content

Commit

Permalink
Make model serializable
Browse files Browse the repository at this point in the history
Close #71
  • Loading branch information
baopham committed Aug 12, 2017
1 parent 37dabf1 commit e051c10
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
22 changes: 22 additions & 0 deletions src/DynamoDbModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -295,4 +295,26 @@ public function setDynamoDbIndexKeys($dynamoDbIndexKeys)
$this->dynamoDbIndexKeys = $dynamoDbIndexKeys;
}

/**
* Remove non-serializable properties when serializing.
*
* @return array
*/
public function __sleep()
{
return array_keys(
array_except(get_object_vars($this), ['client', 'marshaler', 'attributeFilter'])
);
}

/**
* When a model is being unserialized, check if it needs to be booted and setup DynamoDB.
*
* @return void
*/
public function __wakeup()
{
parent::__wakeup();
$this->setupDynamoDb();
}
}
26 changes: 19 additions & 7 deletions tests/DynamoDbModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace BaoPham\DynamoDb\Tests;

use Illuminate\Support\Facades\Cache;

/**
* Class DynamoDbModelTest
*
Expand Down Expand Up @@ -384,17 +386,17 @@ public function testStaticMethods()

public function testConditionContainingIndexKeyAndNonIndexKey()
{
$fooItem = $this->seed([
'name' => ['S' => 'Foo'],
'count' => ['N' => 10],
]);

$barItem = $this->seed([
$this->seed([
'name' => ['S' => 'Bar'],
'count' => ['N' => 11],
]);

$expectedItem = $this->testModel->unmarshalItem($fooItem);
$item = $this->seed([
'name' => ['S' => 'Foo'],
'count' => ['N' => 10],
]);

$expectedItem = $this->testModel->unmarshalItem($item);

$foundItems = $this->testModel
->where('count', 10)
Expand All @@ -405,6 +407,16 @@ public function testConditionContainingIndexKeyAndNonIndexKey()
$this->assertEquals($expectedItem, $foundItems->first()->toArray());
}

public function testSerialize()
{
$item = $this->testModel->unmarshalItem($this->seed());
$serializedItems = serialize($this->testModel->all());
$unserializedItems = unserialize($serializedItems);

$this->assertEquals([$item], $unserializedItems->toArray());
$this->assertInstanceOf(get_class($this->testModel), $unserializedItems->first());
}

protected function seed($attributes = [])
{
$item = [
Expand Down

0 comments on commit e051c10

Please sign in to comment.