Test Failed
Push — master ( e3b206...99d1d4 )
by Enjoys
02:23 queued 23s
created

Required::check()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 10
cc 2
nc 2
nop 1
crap 2.0625
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\Traits\Request;
10
11
/**
12
 * Description of Required
13
 *
14
 * $form->text($name, $title)->addRule('required');
15
 * $form->text($name, $title)->addRule('required', $message);
16
 *
17
 */
18
class Required implements RuleInterface
19
{
20
    use Request;
21
22
    private ?string $message;
23
24 3
    public function __construct(?string $message = null)
25
    {
26 3
        $this->message = $message ?? 'Обязательно для заполнения, или выбора';
27
    }
28
29
30
    /**
31
     * @psalm-suppress PossiblyNullReference
32
     * @param Ruleable&Element $element
33
     * @return bool
34
     */
35 2
    public function validate(Ruleable $element): bool
36
    {
37
        /** @var array $requestData */
38 2
        $requestData = match (strtolower($this->getRequest()->getMethod())) {
39 2
            'get' => $this->getRequest()->getQueryParams(),
40 2
            'post' => $this->getRequest()->getParsedBody(),
41 2
            default => []
42 2
        };
43 2
        $_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

43
        $_value = \getValueByIndexPath($element->/** @scrutinizer ignore-call */ getName(), $requestData);
Loading history...
44 2
        if (!$this->check($_value)) {
45 1
            $element->setRuleError($this->message);
46 1
            return false;
47
        }
48 1
        return true;
49
    }
50
51
52
    /**
53
     * @param mixed $value
54
     * @return bool
55
     */
56 2
    private function check(mixed $value): bool
57
    {
58 2
        if (is_array($value)) {
59
            return count($value) > 0;
60
        }
61 2
        return \trim((string) $value) != '';
62
    }
63
}
64