Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.71% covered (warning)
85.71%
12 / 14
33.33% covered (danger)
33.33%
1 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
Validators
85.71% covered (warning)
85.71%
12 / 14
33.33% covered (danger)
33.33%
1 / 3
5.07
0.00% covered (danger)
0.00%
0 / 1
 registry
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 minItems
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 maxItems
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Validation;
6
7use Celemas\Sire\Contract\Rule;
8use Celemas\Sire\Contract\ValidatesEmpty;
9use Celemas\Sire\Contract\Validation as ValidationContract;
10use Celemas\Sire\Contract\Value;
11use Celemas\Sire\RuleRegistry;
12use Celemas\Sire\Validation;
13use Override;
14
15final 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}