Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
85.71% |
12 / 14 |
|
33.33% |
1 / 3 |
CRAP | |
0.00% |
0 / 1 |
| Validators | |
85.71% |
12 / 14 |
|
33.33% |
1 / 3 |
5.07 | |
0.00% |
0 / 1 |
| registry | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
| minItems | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
2.03 | |||
| maxItems | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
2.03 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Validation; |
| 6 | |
| 7 | use Celemas\Sire\Contract\Rule; |
| 8 | use Celemas\Sire\Contract\ValidatesEmpty; |
| 9 | use Celemas\Sire\Contract\Validation as ValidationContract; |
| 10 | use Celemas\Sire\Contract\Value; |
| 11 | use Celemas\Sire\RuleRegistry; |
| 12 | use Celemas\Sire\Validation; |
| 13 | use Override; |
| 14 | |
| 15 | final class Validators |
| 16 | { |
| 17 | public static function registry(): RuleRegistry |
| 18 | { |
| 19 | return RuleRegistry::withDefaults()->withMany([ |
| 20 | 'minitems' => self::minItems(), |
| 21 | 'maxitems' => self::maxItems(), |
| 22 | ]); |
| 23 | } |
| 24 | |
| 25 | private static function minItems(): Rule |
| 26 | { |
| 27 | return new class implements Rule, ValidatesEmpty { |
| 28 | public string $message { |
| 29 | get => 'Has fewer than the minimum number of {arg1} items'; |
| 30 | } |
| 31 | |
| 32 | #[Override] |
| 33 | public function validate(Value $value, string ...$args): ValidationContract |
| 34 | { |
| 35 | if (!is_array($value->value)) { |
| 36 | return Validation::invalid(); |
| 37 | } |
| 38 | |
| 39 | return Validation::from(count($value->value) >= (int) ($args[0] ?? 0)); |
| 40 | } |
| 41 | }; |
| 42 | } |
| 43 | |
| 44 | private static function maxItems(): Rule |
| 45 | { |
| 46 | return new class implements Rule { |
| 47 | public string $message { |
| 48 | get => 'Has more than the maximum allowed number of {arg1} items'; |
| 49 | } |
| 50 | |
| 51 | #[Override] |
| 52 | public function validate(Value $value, string ...$args): ValidationContract |
| 53 | { |
| 54 | if (!is_array($value->value)) { |
| 55 | return Validation::invalid(); |
| 56 | } |
| 57 | |
| 58 | return Validation::from(count($value->value) <= (int) ($args[0] ?? 0)); |
| 59 | } |
| 60 | }; |
| 61 | } |
| 62 | } |