Skip to content
This repository was archived by the owner on Mar 12, 2024. It is now read-only.

Commit 8a3d76c

Browse files
committed
handle arrays as is
1 parent b3d9193 commit 8a3d76c

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

src/Traits/LoopFunctions.php

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,20 @@ public function arrayToProperties(?array $data, mixed $rescue = null): void
4545
{
4646
collect($data ?? [])
4747
->except($this->ignoreKeys())
48-
->each(
49-
fn ($value, $key) => is_array($value)
50-
? $this->arrayToProperties($value, $rescue)
51-
: $this->assignValue($key, $value, $rescue)
52-
);
48+
->each(function ($value, $key) use ($rescue) {
49+
$propertyType = rescue(
50+
callback: fn () => (
51+
new \ReflectionProperty($this, $key)
52+
)->getType()->getName(),
53+
report: false
54+
);
55+
56+
if (is_array($value) && $propertyType !== 'array') {
57+
$this->arrayToProperties($value, $rescue);
58+
}
59+
60+
$this->assignValue($key, $value, $rescue);
61+
});
5362
}
5463

5564
/**
@@ -65,7 +74,7 @@ private function assignValue(string $key, mixed $value, mixed $rescue = null): v
6574
{
6675
if (property_exists($this, $key)) {
6776
rescue(
68-
fn () => isset($this->{$key}) ?: $this->{$key} = $value,
77+
fn () => ! empty($this->{$key}) ?: $this->{$key} = $value,
6978
$rescue,
7079
config('loop-functions.log') ?? false
7180
);

tests/ArrayMappingTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ class ArrayMappingTest extends TestCase
1212
public string $name;
1313
public ?string $password = null;
1414
public string $next;
15+
public array $array = [];
1516

1617
/** @test */
1718
public function testCanMapAnArrayToProperties()
@@ -63,4 +64,21 @@ public function testAlreadyInitializedPropertiesArentOverridesByNestedArrays()
6364

6465
$this->assertStringContainsString('Michael', $this->name);
6566
}
67+
68+
/** @test */
69+
public function testArrayIsAssignedAsIs()
70+
{
71+
$array = [
72+
'name' => 'Michael Rubel',
73+
'array' => [
74+
'test' => true,
75+
],
76+
];
77+
78+
$this->arrayToProperties($array);
79+
80+
$this->assertStringContainsString('Michael', $this->name);
81+
$this->assertArrayHasKey('test', $this->array);
82+
$this->assertTrue($this->array['test']);
83+
}
6684
}

0 commit comments

Comments
 (0)