Passed
Push — master ( 8242ff...1e3ee6 )
by Peter
02:29
created

ExactlyOne   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 63
rs 10
c 0
b 0
f 0
wmc 14

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setArgs() 0 13 4
B passes() 0 15 7
A getErrorPlaceholders() 0 9 2
A getSlug() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Validation\Rules;
6
7
use InvalidArgumentException;
8
use Opulence\Validation\Rules\IRuleWithArgs;
9
use Opulence\Validation\Rules\IRuleWithErrorPlaceholders;
10
11
class ExactlyOne implements IRuleWithArgs, IRuleWithErrorPlaceholders
12
{
13
    /** @var array The name of the fields to compare to */
14
    protected $fieldNames = [];
15
16
    /**
17
     * @inheritdoc
18
     */
19
    public function getErrorPlaceholders(): array
20
    {
21
        $placeholders = [];
22
23
        foreach ($this->fieldNames as $idx => $fieldName) {
24
            $placeholders['other' . ($idx + 1)] = $fieldName;
25
        }
26
27
        return $placeholders;
28
    }
29
30
    /**
31
     * @inheritdoc
32
     */
33
    public function getSlug(): string
34
    {
35
        return 'exactlyOne';
36
    }
37
38
    /**
39
     * @inheritdoc
40
     */
41
    public function passes($value, array $allValues = []): bool
42
    {
43
        $count = 0;
44
45
        if (is_string($value) && $value) {
46
            $count++;
47
        }
48
49
        foreach ($this->fieldNames as $fieldName) {
50
            if (isset($allValues[$fieldName]) && is_string($allValues[$fieldName]) && $allValues[$fieldName]) {
51
                $count++;
52
            }
53
        }
54
55
        return $count === 1;
56
    }
57
58
    /**
59
     * @inheritdoc
60
     */
61
    public function setArgs(array $args)
62
    {
63
        if (count($args) < 1) {
64
            throw new InvalidArgumentException('Must pass valid field names');
65
        }
66
67
        foreach ($args as $arg) {
68
            if (!is_string($arg)) {
69
                throw new InvalidArgumentException('Must pass valid field names');
70
            }
71
        }
72
73
        $this->fieldNames = $args;
74
    }
75
}
76