Skip to content

Commit

Permalink
Merge pull request #8871 from kenjis/fix-model-casting-TypeError
Browse files Browse the repository at this point in the history
fix: [Model] casting causes TypeError when finding no record
  • Loading branch information
kenjis authored May 10, 2024
2 parents e68553f + 4639608 commit 069e13d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
4 changes: 2 additions & 2 deletions system/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ protected function doFind(bool $singleton, $id = null)
$row = $builder->get()->getResult($this->tempReturnType);
}

if ($useCast) {
if ($useCast && $row !== null) {
$row = $this->convertToReturnType($row, $returnType);

$this->tempReturnType = $returnType;
Expand Down Expand Up @@ -318,7 +318,7 @@ protected function doFirst()

$row = $builder->limit(1, 0)->get()->getFirstRow($this->tempReturnType);

if ($useCast) {
if ($useCast && $row !== null) {
$row = $this->convertToReturnType($row, $returnType);

$this->tempReturnType = $returnType;
Expand Down
30 changes: 30 additions & 0 deletions tests/system/Models/DataConverterModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ public function testFindAsArray(): void
$this->seeInDatabase('user', ['name' => 'Sm9obiBTbWl0aA==']);
}

public function testFindAsArrayReturnsNull(): void
{
$this->createModel(UserCastsTimestampModel::class);
$this->db->table('user')->truncate();

$user = $this->model->find(1);

$this->assertNull($user);
}

/**
* @return int|string Insert ID
*/
Expand Down Expand Up @@ -102,6 +112,16 @@ public function testFindAllAsArray(): void
$this->assertInstanceOf(Time::class, $users[1]['created_at']);
}

public function testFindAllAsArrayReturnsNull(): void
{
$this->createModel(UserCastsTimestampModel::class);
$this->db->table('user')->truncate();

$users = $this->model->findAll();

$this->assertSame([], $users);
}

private function prepareTwoRecords(): void
{
$this->prepareOneRecord();
Expand Down Expand Up @@ -170,6 +190,16 @@ public function testFirstAsArray(): void
$this->assertInstanceOf(Time::class, $user['created_at']);
}

public function testFirstAsArrayReturnsNull(): void
{
$this->createModel(UserCastsTimestampModel::class);
$this->db->table('user')->truncate();

$user = $this->model->first();

$this->assertNull($user);
}

public function testFirstAsObject(): void
{
$this->prepareTwoRecords();
Expand Down

0 comments on commit 069e13d

Please sign in to comment.