Skip to content

Commit aa0ec7f

Browse files
committed
allow to delegate rule validation to (Validated)Control
1 parent 0e1918f commit aa0ec7f

File tree

3 files changed

+41
-4
lines changed

3 files changed

+41
-4
lines changed

src/Forms/Controls/BaseControl.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212
use Nette;
1313
use Nette\Forms\Control;
1414
use Nette\Forms\Form;
15+
use Nette\Forms\Rule;
1516
use Nette\Forms\Rules;
17+
use Nette\Forms\ValidatedControl;
18+
use Nette\Forms\Validator;
1619
use Nette\Utils\Html;
1720
use Stringable;
1821
use function array_unique, explode, func_get_arg, func_num_args, get_parent_class, implode, is_array, sprintf, str_contains;
@@ -38,7 +41,7 @@
3841
* @property-deprecated array $options
3942
* @property-read string $error
4043
*/
41-
abstract class BaseControl extends Nette\ComponentModel\Component implements Control
44+
abstract class BaseControl extends Nette\ComponentModel\Component implements Control, ValidatedControl
4245
{
4346
public static string $idMask = 'frm-%s';
4447

@@ -469,6 +472,16 @@ public function validate(): void
469472
}
470473

471474

475+
public function validateRule(Rule $rule, mixed ...$args): bool
476+
{
477+
$op = $rule->validator;
478+
$cb = is_string($op) && strncmp($op, ':', 1) === 0
479+
? [Validator::class, 'validate' . ltrim($op, ':')]
480+
: $op;
481+
return $cb($this, ...$args);
482+
}
483+
484+
472485
/**
473486
* Adds error message to the list.
474487
*/

src/Forms/Rules.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -339,8 +339,17 @@ private function adjustOperation(Rule $rule): void
339339
private static function getCallback(Rule $rule)
340340
{
341341
$op = $rule->validator;
342-
return is_string($op) && strncmp($op, ':', 1) === 0
343-
? [Validator::class, 'validate' . ltrim($op, ':')]
344-
: $op;
342+
if (!(is_string($op) && strncmp($op, ':', 1) === 0)) {
343+
return $op;
344+
}
345+
346+
if ($rule->control instanceof ValidatedControl) {
347+
return function (...$args) use ($rule) {
348+
array_shift($args); // drop the control
349+
return $rule->control->validateRule($rule, ...$args);
350+
};
351+
}
352+
353+
return [Validator::class, 'validate' . ltrim($op, ':')];
345354
}
346355
}

src/Forms/ValidatedControl.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
/**
4+
* This file is part of the Nette Framework (https://nette.org)
5+
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6+
*/
7+
8+
declare(strict_types=1);
9+
10+
namespace Nette\Forms;
11+
12+
interface ValidatedControl extends Control
13+
{
14+
function validateRule(Rule $rule, mixed ...$args): bool;
15+
}

0 commit comments

Comments
 (0)