Skip to content

Commit 0fe57bf

Browse files
committed
Container::getValue() supports conversion to enums [Close #337]
1 parent bcd18af commit 0fe57bf

File tree

3 files changed

+56
-2
lines changed

3 files changed

+56
-2
lines changed

src/Forms/Container.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,17 +147,18 @@ public function getUntrustedValues(string|object|null $returnType = null, ?array
147147
foreach ($this->getComponents() as $name => $control) {
148148
$allowed = $controls === null || in_array($this, $controls, true) || in_array($control, $controls, true);
149149
$name = (string) $name;
150+
$property = $properties[$name] ?? null;
150151
if (
151152
$control instanceof Control
152153
&& $allowed
153154
&& !$control->isOmitted()
154155
) {
155-
$resultObj->$name = $control->getValue();
156+
$resultObj->$name = Helpers::tryEnumConversion($control->getValue(), $property);
156157

157158
} elseif ($control instanceof self) {
158159
$type = $returnType === self::Array && !$control->mappedType
159160
? self::Array
160-
: (isset($properties[$name]) ? Helpers::getSingleType($properties[$name]) : null);
161+
: ($property ? Helpers::getSingleType($property) : null);
161162
$resultObj->$name = $control->getUntrustedValues($type, $allowed ? null : $controls);
162163
}
163164
}

src/Forms/Helpers.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,21 @@ public static function getSingleType($reflection): ?string
299299
}
300300

301301

302+
/** @internal */
303+
public static function tryEnumConversion(mixed $value, $reflection): mixed
304+
{
305+
if ($value !== null
306+
&& $reflection
307+
&& ($type = Nette\Utils\Type::fromReflection($reflection)?->getSingleName())
308+
&& is_a($type, \BackedEnum::class, allow_string: true)
309+
) {
310+
return $type::from($value);
311+
}
312+
313+
return $value;
314+
}
315+
316+
302317
/** @internal */
303318
public static function getSupportedImages(): array
304319
{
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Forms\Form;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
enum TestEnum: string
13+
{
14+
case Case1 = 'case 1';
15+
case Case2 = 'case 2';
16+
}
17+
18+
class FormWithEnum
19+
{
20+
public function __construct(
21+
public TestEnum $enum1,
22+
public ?TestEnum $enum2,
23+
) {
24+
}
25+
}
26+
27+
28+
test('getValues() + enum', function () {
29+
$form = new Form;
30+
$form->addText('enum1');
31+
$form->addText('enum2')->setNullable();
32+
$form->setValues(['enum1' => 'case 1', 'enum2' => null]);
33+
34+
Assert::equal(new FormWithEnum(
35+
enum1: TestEnum::Case1,
36+
enum2: null,
37+
), $form->getValues(FormWithEnum::class));
38+
});

0 commit comments

Comments
 (0)