Skip to content

Commit 15f9c86

Browse files
authored
perf: reduce closure invocation overhead in DataConverter::reconstruct() for plain objects (#10754)
1 parent 1a36611 commit 15f9c86

2 files changed

Lines changed: 34 additions & 5 deletions

File tree

‎system/DataConverter/DataConverter.php‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,13 @@ public function reconstruct(string $classname, array $row): object
149149
return $classObj;
150150
}
151151

152-
$classSet = Closure::bind(function ($key, $value): void {
153-
$this->{$key} = $value;
152+
$classSet = Closure::bind(function (array $data): void {
153+
foreach ($data as $key => $value) {
154+
$this->{$key} = $value;
155+
}
154156
}, $classObj, $classname);
155157

156-
foreach ($phpData as $key => $value) {
157-
$classSet($key, $value);
158-
}
158+
$classSet($phpData);
159159

160160
return $classObj;
161161
}

‎tests/system/DataConverter/DataConverterTest.php‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -797,6 +797,35 @@ public function testReconstructObjectWithClosure(): void
797797
$this->assertInstanceOf(Time::class, $obj->updated_at);
798798
}
799799

800+
public function testReconstructPlainObject(): void
801+
{
802+
$types = [
803+
'id' => 'int',
804+
'status' => 'int',
805+
];
806+
$converter = $this->createDataConverter($types, [], null, null);
807+
808+
$plainClass = new class () {
809+
public int $id;
810+
public int $status;
811+
public string $name;
812+
};
813+
814+
$dbData = [
815+
'id' => '123',
816+
'status' => '1',
817+
'name' => 'Alice',
818+
];
819+
820+
/** @var object{id: int, status: int, name: string} $obj */
821+
$obj = $converter->reconstruct($plainClass::class, $dbData);
822+
823+
$this->assertInstanceOf($plainClass::class, $obj);
824+
$this->assertSame(123, $obj->id);
825+
$this->assertSame(1, $obj->status);
826+
$this->assertSame('Alice', $obj->name);
827+
}
828+
800829
public function testExtract(): void
801830
{
802831
$types = [

0 commit comments

Comments
 (0)