Skip to content

Commit 52967f3

Browse files
author
Яценко Андрей
committed
Fix: nullable array
1 parent 1cfef31 commit 52967f3

File tree

3 files changed

+20
-7
lines changed

3 files changed

+20
-7
lines changed

src/ClassTransformer.php

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,8 @@ private static function dataConverting(string $className, ...$args)
168168
} else {
169169
$arrayType = self::getClassFromPhpDoc($property->getDocComment());
170170
}
171-
if (!empty($arrayType)) {
172-
if (self::propertyIsScalar($arrayType)) {
173-
$instance->{$item->name} = $value;
174-
continue;
175-
}
171+
172+
if (!empty($arrayType) && !empty($value) && !self::propertyIsScalar($arrayType)) {
176173
foreach ($value as $el) {
177174
/** @phpstan-ignore-next-line */
178175
$instance->{$item->name}[] = self::dataConverting($arrayType, $el);

tests/ClassTransformerFromArrayTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,19 @@ public function testScalarArray(): void
5050
self::assertInstanceOf(ArrayScalarDTO::class, $userDTO);
5151
}
5252

53+
/**
54+
* @throws ReflectionException|ClassNotFoundException
55+
*/
56+
public function testNullArray(): void
57+
{
58+
$data = [
59+
'id' => 1,
60+
'products' => null
61+
];
62+
$userDTO = ClassTransformer::transform(ArrayScalarDTO::class, $data);
63+
self::assertInstanceOf(ArrayScalarDTO::class, $userDTO);
64+
}
65+
5366
/**
5467
* @throws ReflectionException|ClassNotFoundException
5568
*/

tests/DTO/ArrayScalarDTO.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33

44
namespace Tests\DTO;
55

6+
use ClassTransformer\Attributes\ConvertArray;
7+
68
class ArrayScalarDTO
79
{
810
public $id;
911

10-
/** @var array<string> */
11-
public array $history;
12+
/** @var null|array<string> */
13+
#[ConvertArray('string')]
14+
public ?array $products;
1215
}

0 commit comments

Comments
 (0)