Skip to content

Commit 39af165

Browse files
committed
Container::getValues($obj) to hydrate object
1 parent 0d00d8e commit 39af165

2 files changed

Lines changed: 40 additions & 9 deletions

File tree

src/Forms/Container.php

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -102,31 +102,41 @@ public function setValues($data, bool $erase = false)
102102

103103
/**
104104
* Returns the values submitted by the form.
105-
* @param string|null $returnType 'array' for array
105+
* @param string|object|null $returnType 'array' for array
106+
106107
* @return object|array
107108
*/
108109
public function getValues($returnType = null)
109110
{
110-
$returnType = $returnType
111-
? ($returnType === true ? self::ARRAY : $returnType) // back compatibility
112-
: ($this->mappedType ?? ArrayHash::class);
111+
if ($returnType === self::ARRAY || $returnType === true || $this->mappedType === self::ARRAY) {
112+
$returnType = self::ARRAY;
113+
$obj = new \stdClass;
113114

114-
$isArray = $returnType === self::ARRAY;
115-
$obj = $isArray ? new \stdClass : new $returnType;
116-
$rc = new \ReflectionClass($obj);
115+
} elseif (is_object($returnType)) {
116+
$obj = $returnType;
117+
118+
} else {
119+
$returnType = ($returnType ?? $this->mappedType ?? ArrayHash::class);
120+
$obj = new $returnType;
121+
}
117122

123+
$rc = new \ReflectionClass($obj);
118124
foreach ($this->getComponents() as $name => $control) {
119125
$name = (string) $name;
120126
if ($control instanceof Control && !$control->isOmitted()) {
121127
$obj->$name = $control->getValue();
128+
122129
} elseif ($control instanceof self) {
123-
$type = $isArray && !$control->mappedType
130+
$type = $returnType === self::ARRAY && !$control->mappedType
124131
? self::ARRAY
125132
: ($rc->hasProperty($name) ? Nette\Utils\Reflection::getPropertyType($rc->getProperty($name)) : null);
126133
$obj->$name = $control->getValues($type);
127134
}
128135
}
129-
return $isArray ? (array) $obj : $obj;
136+
137+
return $returnType === self::ARRAY
138+
? (array) $obj
139+
: $obj;
130140
}
131141

132142

tests/Forms/Container.values.mapping.phpt

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

0 commit comments

Comments
 (0)