diff --git a/src/Make/InitData.php b/src/Make/InitData.php index 85416f1..1c5bf67 100644 --- a/src/Make/InitData.php +++ b/src/Make/InitData.php @@ -11,7 +11,7 @@ abstract class InitData extends Make /** * @param array $props */ - public function __construct(array $props) + public function __construct(array $props = []) { foreach ($props as $prop => $value) { $value = match ($prop) { diff --git a/src/Make/Make.php b/src/Make/Make.php index 3ca3fae..f7b4c39 100644 --- a/src/Make/Make.php +++ b/src/Make/Make.php @@ -9,7 +9,7 @@ abstract class Make extends Arrayable /** * @param array $props */ - public function __construct(array $props) + public function __construct(array $props = []) { foreach ($props as $prop => $value) { $this->setProperty(camelize($prop), $value); diff --git a/src/Support/Arrayable.php b/src/Support/Arrayable.php index c39ba85..e32e05d 100644 --- a/src/Support/Arrayable.php +++ b/src/Support/Arrayable.php @@ -4,6 +4,7 @@ use ReflectionClass; use ReflectionProperty; +use TgWebValid\Make\Make; abstract class Arrayable { @@ -26,12 +27,7 @@ public function toArray(?object $object = null): array $name = $property->getName(); $value = $object->$name ?? null; $result[$name] = match(true) { - is_object($value) => $this->toArray($value), - is_array($value) => array_map(function($item) { - return is_object($item) - ? $this->toArray($item) - : $item; - }, $value), + $value instanceof Make => $this->toArray($value), default => $value }; } diff --git a/tests/Support/ArrayableTest.php b/tests/Support/ArrayableTest.php index ff167e9..dd90cdc 100644 --- a/tests/Support/ArrayableTest.php +++ b/tests/Support/ArrayableTest.php @@ -3,6 +3,8 @@ namespace TgWebValid\Test\Support; use PHPUnit\Framework\TestCase; +use stdClass; +use TgWebValid\Make\Make; use TgWebValid\Support\Arrayable; final class ArrayableTest extends TestCase @@ -58,13 +60,18 @@ public function testPropertyAccess(): void public function testPropertyDeep(): object { - $user = new class + $user = new class ($this->createStdClass()) extends Make { public int $id; public string $firstName = 'Сергій'; + public function __construct( + public stdClass $stdClass + ) + { + } }; - $initData = new class ($user) + $initData = new class ($user) extends Make { public ?string $queryId = null; public function __construct( @@ -88,7 +95,8 @@ public function __construct( 'queryId' => null, 'user' => [ 'id' => null, - 'firstName' => 'Сергій' + 'firstName' => 'Сергій', + 'stdClass' => $this->createStdClass() ] ] ], $arrayable->toArray()); @@ -107,9 +115,17 @@ public function testAlien(object $object): void 'queryId' => null, 'user' => [ 'id' => null, - 'firstName' => 'Сергій' + 'firstName' => 'Сергій', + 'stdClass' => $this->createStdClass() ] ] ], $arrayable->toArray($object)); } + + public function createStdClass(): stdClass + { + $stdClass = new stdClass; + $stdClass->field = 'test'; + return $stdClass; + } }