1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Helper; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use IteratorAggregate; |
9
|
|
|
use Traversable; |
10
|
|
|
use Yiisoft\Validator\Rule\Callback; |
11
|
|
|
use Yiisoft\Validator\RuleInterface; |
12
|
|
|
use Yiisoft\Validator\SkipOnEmptyInterface; |
13
|
|
|
|
14
|
|
|
use function is_callable; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @internal |
18
|
|
|
* |
19
|
|
|
* @template-implements IteratorAggregate<int, RuleInterface> |
20
|
|
|
*/ |
21
|
|
|
final class RulesNormalizerIterator implements IteratorAggregate |
22
|
|
|
{ |
23
|
|
|
private $defaultSkipOnEmptyCriteria; |
24
|
|
|
|
25
|
|
|
public function __construct( |
26
|
|
|
private iterable $rules, |
27
|
|
|
?callable $defaultSkipOnEmptyCriteria = null |
28
|
|
|
) { |
29
|
|
|
$this->defaultSkipOnEmptyCriteria = $defaultSkipOnEmptyCriteria; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function getIterator(): Traversable |
33
|
|
|
{ |
34
|
|
|
/** @var mixed $rule */ |
35
|
|
|
foreach ($this->rules as $rule) { |
36
|
|
|
yield self::normalizeRule($rule, $this->defaultSkipOnEmptyCriteria); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @throws InvalidArgumentException |
42
|
|
|
*/ |
43
|
|
|
private static function normalizeRule(mixed $rule, ?callable $defaultSkipOnEmptyCriteria): RuleInterface |
44
|
|
|
{ |
45
|
|
|
if (is_callable($rule)) { |
46
|
|
|
return new Callback($rule); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (!$rule instanceof RuleInterface) { |
50
|
|
|
throw new InvalidArgumentException( |
51
|
|
|
sprintf( |
52
|
|
|
'Rule should be either an instance of %s or a callable, %s given.', |
53
|
|
|
RuleInterface::class, |
54
|
|
|
get_debug_type($rule) |
55
|
|
|
) |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
if ( |
60
|
|
|
$defaultSkipOnEmptyCriteria !== null |
61
|
|
|
&& $rule instanceof SkipOnEmptyInterface |
62
|
|
|
&& $rule->getSkipOnEmpty() === null |
63
|
|
|
) { |
64
|
|
|
$rule = $rule->skipOnEmpty($defaultSkipOnEmptyCriteria); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $rule; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|