Skip to content

Commit 18adb95

Browse files
authored
Merge pull request #30 from spotlibs/feature/exploration
dtos filter array key by properties
2 parents fc67386 + 654a08a commit 18adb95

File tree

3 files changed

+19
-14
lines changed

3 files changed

+19
-14
lines changed

src/Dtos/TraitConvertibleDtos.php

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,16 @@ public function __construct(array $data = [])
4040
{
4141
$reflector = new ReflectionClass(static::class);
4242
foreach ($data as $key => $value) {
43-
try {
44-
$prop = $reflector->getProperty($key);
45-
} catch (Throwable) {
46-
// array key is not one of constructed DTO's property name
47-
continue;
43+
if (property_exists($this, $key)) {
44+
try {
45+
$prop = $reflector->getProperty($key);
46+
} catch (Throwable) {
47+
// array key is not one of constructed DTO's property name
48+
continue;
49+
}
50+
$value = TypeConverter::assertType($value, $reflector, $prop);
51+
$this->{$key} = $value;
4852
}
49-
$value = TypeConverter::assertType($value, $reflector, $prop);
50-
$this->{$key} = $value;
5153
}
5254
}
5355

src/Dtos/TraitDtos.php

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,17 @@ public function __construct(array $data = [])
3939
{
4040
$reflector = new ReflectionClass(static::class);
4141
foreach ($data as $key => $value) {
42-
if (is_array($value)) {
43-
$prop = $reflector->getProperty($key);
44-
$type = $prop->getType()->getName();
45-
//construct object if type is not array
46-
if ($type != 'array') {
47-
$value = new $type($value);
42+
if (property_exists($this, $key)) {
43+
if (is_array($value)) {
44+
$prop = $reflector->getProperty($key);
45+
$type = $prop->getType()->getName();
46+
//construct object if type is not array
47+
if ($type != 'array') {
48+
$value = new $type($value);
49+
}
4850
}
51+
$this->{$key} = $value;
4952
}
50-
$this->{$key} = $value;
5153
}
5254
}
5355

tests/Dtos/DtosTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ public function testDtoNestedArray(): void
171171
'name' => 'Bruce',
172172
'employeeId' => 1,
173173
'isActive' => true,
174+
'friend' => 'Yuri',
174175
'relatives' => ['robert', 'lana', 'garry'],
175176
'partner' => [
176177
'name' => 'Amanda',

0 commit comments

Comments
 (0)