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

Required   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 16
c 1
b 0
f 0
dl 0
loc 37
ccs 17
cts 18
cp 0.9444
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 13 2
A setMessage() 0 6 2
A check() 0 6 2
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
 * Description of Required
13
 *
14
 * $form->text($name, $title)->addRule('required');
15
 * $form->text($name, $title)->addRule('required', $message);
16
 *
17
 */
18
class Required extends Rules implements RuleInterface
19
{
20 16
    public function setMessage(?string $message = null): ?string
21
    {
22 16
        if (is_null($message)) {
23 16
            $message = 'Обязательно для заполнения, или выбора';
24
        }
25 16
        return parent::setMessage($message);
26
    }
27
    /**
28
     * @psalm-suppress PossiblyNullReference
29
     * @param Ruleable&Element $element
30
     * @return bool
31
     */
32 10
    public function validate(Ruleable $element): bool
33
    {
34 10
        $requestData = match (strtolower($this->getRequest()->getRequest()->getMethod())) {
35 9
            'get' => $this->getRequest()->getQueryData()->toArray(),
36 1
            'post' => $this->getRequest()->getPostData()->toArray(),
37
            default => []
38
        };
39 10
        $_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

39
        $_value = \getValueByIndexPath($element->/** @scrutinizer ignore-call */ getName(), $requestData);
Loading history...
40 10
        if (!$this->check($_value)) {
41 6
            $element->setRuleError($this->getMessage());
42 6
            return false;
43
        }
44 6
        return true;
45
    }
46
47
48
49 14
    private function check($value): bool
50
    {
51 14
        if (is_array($value)) {
52 3
            return count($value) > 0;
53
        }
54 11
        return \trim((string) $value) != '';
55
    }
56
}
57