Skip to content

Commit

Permalink
Validator: added support for enums (#282)
Browse files Browse the repository at this point in the history
Co-authored-by: martin.sedlacek <martin.sedlacek@motv.eu>
  • Loading branch information
2 people authored and dg committed May 4, 2022
1 parent 29e3ebd commit b8bbc79
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Forms/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ public static function validateEqual(Control $control, $arg): bool

foreach ($values as $val) {
foreach ($args as $item) {
if ($item instanceof \BackedEnum) {
$item = $item->value;
}

if ((string) $val === (string) $item) {
continue 2;
}
Expand Down
38 changes: 38 additions & 0 deletions tests/Forms/Controls.BaseControl.enum.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/**
* Test: Nette\Forms\Controls\BaseControl & enum
* @phpVersion 8.1
*/

declare(strict_types=1);

use Nette\Forms\Form;
use Nette\Forms\Validator;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


enum TestEnum: string
{
case CASE_1 = 'case 1';
case CASE_2 = 'case 2';
}


before(function () {
Form::initialize(true);
});


test('validators for enums', function () {
$form = new Form;
$input = $form->addText('text');
$input->setValue(TestEnum::CASE_1->value);

Assert::true(Validator::validateEqual($input, TestEnum::CASE_1));
Assert::true(Validator::validateEqual($input, 'case 1'));
Assert::false(Validator::validateEqual($input, TestEnum::CASE_2));
Assert::false(Validator::validateEqual($input, 1));
});

0 comments on commit b8bbc79

Please sign in to comment.