Skip to content

Commit 80f0578

Browse files
author
František Mazura
committed
root element
1 parent afecfd1 commit 80f0578

File tree

3 files changed

+10
-8
lines changed

3 files changed

+10
-8
lines changed

src/AbstractValueObject.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,6 @@ public function init($data): self
6666
foreach ($data as $name => $item) {
6767
$setter = "set" . ucfirst($name);
6868
$value = $data[$name] ?? null;
69-
if ($name == self::ROOT) {
70-
$value = $data;
71-
}
7269
$this->setTouched($name);
7370
try {
7471
if (method_exists($this, $setter)) {
@@ -110,6 +107,11 @@ public function toArray(): array
110107
if ($this->isIgnoredAttr($name)) {
111108
continue;
112109
}
110+
// if ROOT do not print inside root attribute
111+
if ($name == self::ROOT && $item instanceof ValueObjectInterface) {
112+
$out = $item->toArray();
113+
break;
114+
}
113115
// ValueObject element
114116
if ($item instanceof AbstractValueObject) {
115117
$out[$name] = $item->toArray();
@@ -219,7 +221,7 @@ private static function transformBuildInType(ReflectionParameter $reflectionPara
219221
private static function initAndValidateValueObject(object $obj, string $setter, ReflectionParameter $parameter, $data)
220222
{
221223
$type = $parameter->getType()->getName();
222-
if (is_subclass_of($type, AbstractValueObject::class)) {
224+
if (is_subclass_of($type, ValueObjectInterface::class)) {
223225
if (empty($data) && !is_array($data)) {
224226
if ($parameter->allowsNull()) {
225227
return;

tests/ValueObjectTest.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
use OGSoft\ValueObjects\Exceptions\ValidatorException;
77
use PHPUnit\Framework\TestCase;
88
use Tests\ValueObjects\CarValueObject;
9-
use Tests\ValueObjects\TireValueObject;
9+
use Tests\ValueObjects\RootValueObject;
1010

1111
final class ValueObjectTest extends TestCase
1212
{
@@ -70,8 +70,8 @@ public function testRoot()
7070
{
7171
$data = ["winter" => true];
7272

73-
$tire = new TireValueObject();
74-
$tire->init($data);
73+
$tire = new RootValueObject();
74+
$tire->init(["root" => $data]);
7575
$this->assertEquals($data, $tire->toArray());
7676
}
7777
}

tests/ValueObjects/RootValueObject.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
namespace Tests\ValueObjects;
55

66

7-
class RootValueObject
7+
class RootValueObject extends AbstractMyValueObject
88
{
99
/**
1010
* @var TireValueObject

0 commit comments

Comments
 (0)