Skip to content

Commit

Permalink
feat(Model, experimental): 增加模型序列化
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed Dec 23, 2023
1 parent 4e5c3a7 commit d7a7246
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/ModelTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,30 @@ public function __unset($name): void
$this->unsetAttribute($name);
}

/**
* @return array
* @experimental *NOT* all properties will be serialized now
*/
public function __serialize(): array
{
return [
'coll' => $this->isColl(),
'id' => $this->isColl() ? $this->getAll($this->getPrimaryKey()) : $this->get($this->getPrimaryKey()),
];
}

/**
* @param array $data
* @return void
* @experimental
*/
public function __unserialize(array $data): void
{
$this->__construct();
$this->reload();
$data['coll'] ? $this->findAll($data['id']) : $this->find($data['id']);
}

/**
* Set each attribute value, without checking whether the column is fillable, and save the model
*
Expand Down
20 changes: 20 additions & 0 deletions tests/unit/Model/CollTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -603,4 +603,24 @@ public function testNewModelWontChangeToColl()
TestUser::new(),
]);
}

public function testSerialize()
{
$this->initFixtures();

$users = TestUser::new()->limit(2)->all();

$data = serialize($users);

$users2 = unserialize($data);
$this->assertSame($users->count(), $users2->count());

$sql = $users2->getSql();
$this->assertSqlSame('SELECT * FROM `test_users` WHERE `id` IN (?, ?)', $sql);
}

protected function assertSqlSame($expected, $actual, string $message = '')
{
$this->assertSame($expected, str_replace($this->db->getTablePrefix(), '', $actual), $message);
}
}
21 changes: 21 additions & 0 deletions tests/unit/Model/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -935,4 +935,25 @@ public function testTableHasDatabase()
$data = $user->fetch();
$this->assertNotEmpty($data);
}

public function testSerialize()
{
$this->initFixtures();

$user = TestUser::first();

$data = serialize($user);
$this->assertStringContainsString((string) $user->id, $data);

$user2 = unserialize($data);
$this->assertSame($user->id, $user2->id);

$sql = $user2->getSql();
$this->assertSqlSame('SELECT * FROM `test_users` WHERE `id` = ? LIMIT 1', $sql);
}

protected function assertSqlSame($expected, $actual, string $message = '')
{
$this->assertSame($expected, str_replace($this->db->getTablePrefix(), '', $actual), $message);
}
}

0 comments on commit d7a7246

Please sign in to comment.