Passed
Push — master ( f360f0...1bc594 )
by Bruno
06:10
created

RequiredWithAll::validate()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 14
c 1
b 0
f 0
nc 17
nop 3
dl 0
loc 22
ccs 15
cts 15
cp 1
crap 7
rs 8.8333
1
<?php declare(strict_types=1);
2
3
namespace Formularium\Validator;
4
5
use Formularium\Exception\ValidatorException;
6
use Formularium\Field;
7
use Formularium\Model;
8
use Formularium\ValidatorInterface;
9
10
/**
11
 * The field under validation must be present and not empty only if all of the other specified fields are present.
12
 */
13
class RequiredWithAll implements ValidatorInterface
14
{
15 2
    public function validate($value, Field $field, Model $model = null)
16
    {
17 2
        if ($field->getValidators()[self::class] ?? false) {
18 2
            $expectedFields = $field->getValidators()[self::class];
19 2
            if (!is_array($expectedFields)) {
20 1
                $expectedFields = [$expectedFields];
21
            }
22 2
            $found = true;
23 2
            $data = $model->getData();
0 ignored issues
show
Bug introduced by
The method getData() does not exist on null. ( Ignorable by Annotation )

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

23
            /** @scrutinizer ignore-call */ 
24
            $data = $model->getData();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
24 2
            foreach ($expectedFields as $ef) {
25 2
                if (!array_key_exists($ef, $data)) {
26 1
                    $found = false;
27 2
                    break;
28
                }
29
            }
30
31 2
            if ($found && empty($value)) {
32 1
                $name = $field->getName();
33 1
                throw new ValidatorException("Field $name is required when all fields " . implode(',', $expectedFields) . ' are present');
34
            }
35
        }
36 1
        return $value;
37
    }
38
}
39