Passed
Push — 5.x ( 65a76f...3a1e20 )
by Enjoys
59s queued 13s
created

Equal   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 22
c 1
b 0
f 0
dl 0
loc 51
ccs 22
cts 24
cp 0.9167
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 17 2
A setMessage() 0 6 2
A check() 0 16 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Forms\Rule;
6
7
use Enjoys\Forms\Element;
8
use Enjoys\Forms\Interfaces\Ruleable;
9
use Enjoys\Forms\Rules;
10
11
/**
12
 * @example
13
 * new Equal($message, ['expect']); or
14
 * new Equal($message, (array) 'expect'); or
15
 * new Equal($message, ['expect', 1, '255']);
16
 */
17
class Equal extends Rules implements RuleInterface
18
{
19 13
    public function setMessage(?string $message = null): ?string
20
    {
21 13
        if (is_null($message)) {
22 13
            $message = 'Допустимые значения (указаны через запятую): ' . \implode(', ', $this->getParams());
23
        }
24 13
        return parent::setMessage($message);
25
    }
26
27
    /**
28
     * @psalm-suppress PossiblyNullReference
29
     * @param Ruleable&Element $element
30
     * @return bool
31
     */
32 13
    public function validate(Ruleable $element): bool
33
    {
34
35 13
        $method = $this->getRequest()->getRequest()->getMethod();
36 13
        $requestData = match (strtolower($method)) {
37 13
            'get' => $this->getRequest()->getQueryData()->toArray(),
38
            'post' => $this->getRequest()->getPostData()->toArray(),
39
            default => []
40
        };
41 13
        $value = \getValueByIndexPath($element->getName(), $requestData);
0 ignored issues
show
Bug introduced by
The method getName() does not exist on Enjoys\Forms\Interfaces\Ruleable. Since it exists in all sub-types, consider adding an abstract or default implementation to Enjoys\Forms\Interfaces\Ruleable. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

41
        $value = \getValueByIndexPath($element->/** @scrutinizer ignore-call */ getName(), $requestData);
Loading history...
42
43 13
        if (false === $this->check($value)) {
44 5
            $element->setRuleError($this->getMessage());
45 5
            return false;
46
        }
47
48 8
        return true;
49
    }
50
51
52 13
    private function check($value)
53
    {
54
55 13
        if ($value === false) {
56 1
            return true;
57
        }
58 12
        if (is_array($value)) {
59 4
            foreach ($value as $_val) {
60 4
                if (false === $this->check($_val)) {
61 1
                    return false;
62
                }
63
            }
64 3
            return true;
65
        }
66
67 12
        return array_search($value, $this->getParams());
68
    }
69
}
70