Skip to content

Commit a069c66

Browse files
committed
Fixed the bug with array casting for nested objects
1 parent e204655 commit a069c66

File tree

3 files changed

+27
-8
lines changed

3 files changed

+27
-8
lines changed

src/DtoSerialize.php

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,21 +37,37 @@ public static function serializeSingle( Dto $dto ): \stdClass
3737

3838
/**
3939
* @param Dto $dto
40+
* @param array $arr
4041
* @return array
4142
*/
42-
public static function castToArray( Dto $dto ): array
43+
public static function castToArray( Dto $dto, array $arr = [] ): array
4344
{
44-
$arr = [];
45-
46-
$vars = get_object_vars($dto);
45+
$vars = $dto->getObjectVars();
4746

4847
foreach ( $vars as $key => $value )
4948
{
5049
$key = str_replace('_', '', $key);
50+
$temp = [];
5151

52-
$arr[$key] = $value;
52+
if($value instanceof Dto)
53+
{
54+
$temp = self::castToArray($value, $temp);
55+
$arr[$key] = $temp;
56+
}
57+
else
58+
{
59+
$arr[$key] = $value;
60+
}
5361
}
5462

5563
return $arr;
5664
}
65+
66+
/**
67+
* @return array
68+
*/
69+
public function getObjectVars(): array
70+
{
71+
return get_object_vars($this);
72+
}
5773
}

src/ToArray.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@ trait ToArray
1010
* @param bool $toSnakeCase
1111
* @return array
1212
*/
13-
public function toArray($toSnakeCase = true): array
13+
public function toArray(bool $toSnakeCase = true): array
1414
{
15+
$arr = self::castToArray($this);
16+
1517
if($toSnakeCase)
1618
{
1719
$result = [];
1820

19-
foreach (self::castToArray($this) as $key => $value)
21+
foreach ($arr as $key => $value)
2022
{
2123
$key = ltrim(strtolower(preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $key)), '_');
2224

@@ -26,6 +28,6 @@ public function toArray($toSnakeCase = true): array
2628
return $result;
2729
}
2830

29-
return self::castToArray($this);
31+
return $arr;
3032
}
3133
}

versionlog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* Installed the [codebot/enum](https://github.com/c0d3b0t/phpenum) package.
55
* Enhanced unit tests coverage.
66
* Changed the required PHP version to >=8.0.
7+
* Fixed the bug with array casting for nested objects.
78

89
## 0.2.3 2021-03-26
910
* Fixed bugs related to generated constructor props.

0 commit comments

Comments
 (0)