Skip to content

Commit 069e13d

Browse files
authored
Merge pull request #8871 from kenjis/fix-model-casting-TypeError
fix: [Model] casting causes TypeError when finding no record
2 parents e68553f + 4639608 commit 069e13d

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

system/Model.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ protected function doFind(bool $singleton, $id = null)
210210
$row = $builder->get()->getResult($this->tempReturnType);
211211
}
212212

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

216216
$this->tempReturnType = $returnType;
@@ -318,7 +318,7 @@ protected function doFirst()
318318

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

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

324324
$this->tempReturnType = $returnType;

tests/system/Models/DataConverterModelTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ public function testFindAsArray(): void
4343
$this->seeInDatabase('user', ['name' => 'Sm9obiBTbWl0aA==']);
4444
}
4545

46+
public function testFindAsArrayReturnsNull(): void
47+
{
48+
$this->createModel(UserCastsTimestampModel::class);
49+
$this->db->table('user')->truncate();
50+
51+
$user = $this->model->find(1);
52+
53+
$this->assertNull($user);
54+
}
55+
4656
/**
4757
* @return int|string Insert ID
4858
*/
@@ -102,6 +112,16 @@ public function testFindAllAsArray(): void
102112
$this->assertInstanceOf(Time::class, $users[1]['created_at']);
103113
}
104114

115+
public function testFindAllAsArrayReturnsNull(): void
116+
{
117+
$this->createModel(UserCastsTimestampModel::class);
118+
$this->db->table('user')->truncate();
119+
120+
$users = $this->model->findAll();
121+
122+
$this->assertSame([], $users);
123+
}
124+
105125
private function prepareTwoRecords(): void
106126
{
107127
$this->prepareOneRecord();
@@ -170,6 +190,16 @@ public function testFirstAsArray(): void
170190
$this->assertInstanceOf(Time::class, $user['created_at']);
171191
}
172192

193+
public function testFirstAsArrayReturnsNull(): void
194+
{
195+
$this->createModel(UserCastsTimestampModel::class);
196+
$this->db->table('user')->truncate();
197+
198+
$user = $this->model->first();
199+
200+
$this->assertNull($user);
201+
}
202+
173203
public function testFirstAsObject(): void
174204
{
175205
$this->prepareTwoRecords();

0 commit comments

Comments
 (0)