Skip to content

Commit 592148e

Browse files
committed
added Container::hydrate()
1 parent dd4c8ee commit 592148e

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

src/Forms/Container.php

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,14 +107,22 @@ public function setValues($data, bool $erase = false)
107107
*/
108108
public function getValues($returnType = null)
109109
{
110-
$returnType = $returnType
111-
? ($returnType === true ? self::ARRAY : $returnType) // back compatibility
112-
: ($this->mappedType ?? ArrayHash::class);
110+
if ($returnType === self::ARRAY || $returnType === true || $this->mappedType === self::ARRAY) {
111+
$obj = new \stdClass;
112+
$this->hydrate($obj, true);
113+
return (array) $obj;
114+
} else {
115+
$obj = new ($returnType ?? $this->mappedType ?? ArrayHash::class);
116+
$this->hydrate($obj);
117+
return $obj;
118+
}
119+
}
113120

114-
$isArray = $returnType === self::ARRAY;
115-
$obj = $isArray ? new \stdClass : new $returnType;
116-
$rc = new \ReflectionClass($obj);
117121

122+
public function hydrate(object $obj): void
123+
{
124+
$isArray = func_get_args()[1] ?? false;
125+
$rc = new \ReflectionClass($obj);
118126
foreach ($this->getComponents() as $name => $control) {
119127
$name = (string) $name;
120128
if ($control instanceof IControl && !$control->isOmitted()) {
@@ -126,7 +134,6 @@ public function getValues($returnType = null)
126134
$obj->$name = $control->getValues($type);
127135
}
128136
}
129-
return $isArray ? (array) $obj : $obj;
130137
}
131138

132139

tests/Forms/Container.values.mapping.phpt

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,3 +314,23 @@ test('onSuccess test', function () {
314314
$form->fireEvents();
315315
Assert::true($ok);
316316
});
317+
318+
319+
test('hydrate', function () {
320+
$_SERVER['REQUEST_METHOD'] = 'POST';
321+
322+
$form = createForm();
323+
$obj = new FormData;
324+
$form->hydrate($obj);
325+
326+
Assert::equal(hydrate(FormData::class, [
327+
'title' => 'sent title',
328+
'first' => ArrayHash::from([
329+
'name' => '',
330+
'age' => '999',
331+
'second' => ArrayHash::from([
332+
'city' => 'sent city',
333+
]),
334+
]),
335+
]), $obj);
336+
});

0 commit comments

Comments
 (0)