Skip to content

Commit afecfd1

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

File tree

4 files changed

+51
-1
lines changed

4 files changed

+51
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,5 @@ PHP Value object for storing valid data.
2525
- add interface `ValueObjectInterface`
2626
- remove trait
2727
- min request PHP 7.4
28-
- check null
28+
- check null
29+
- root element

src/AbstractValueObject.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@
1616

1717
abstract class AbstractValueObject implements ValueObjectInterface
1818
{
19+
/**
20+
* it is used if value object contains single value object
21+
*/
22+
const ROOT = "root";
23+
1924
private array $touched = [];
2025
private array $ignoredAttrs = ["ignoredAttrs", "touched"];
2126

@@ -61,6 +66,9 @@ public function init($data): self
6166
foreach ($data as $name => $item) {
6267
$setter = "set" . ucfirst($name);
6368
$value = $data[$name] ?? null;
69+
if ($name == self::ROOT) {
70+
$value = $data;
71+
}
6472
$this->setTouched($name);
6573
try {
6674
if (method_exists($this, $setter)) {

tests/ValueObjectTest.php

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

1011
final class ValueObjectTest extends TestCase
1112
{
@@ -64,5 +65,14 @@ public function testNull()
6465
$car->init($data);
6566
$this->assertTrue(true);
6667
}
68+
69+
public function testRoot()
70+
{
71+
$data = ["winter" => true];
72+
73+
$tire = new TireValueObject();
74+
$tire->init($data);
75+
$this->assertEquals($data, $tire->toArray());
76+
}
6777
}
6878

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
4+
namespace Tests\ValueObjects;
5+
6+
7+
class RootValueObject
8+
{
9+
/**
10+
* @var TireValueObject
11+
*/
12+
protected $root;
13+
14+
/**
15+
* @return TireValueObject
16+
*/
17+
public function getRoot(): TireValueObject
18+
{
19+
return $this->root;
20+
}
21+
22+
/**
23+
* @param TireValueObject $root
24+
* @return RootValueObject
25+
*/
26+
public function setRoot(TireValueObject $root): RootValueObject
27+
{
28+
$this->root = $root;
29+
return $this;
30+
}
31+
}

0 commit comments

Comments
 (0)