Passed
Push — master ( 2380e5...c08ae0 )
by Bruno
12:55 queued 04:33
created

RequiredWithAll   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 91.3%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 22
c 2
b 0
f 0
dl 0
loc 38
ccs 21
cts 23
cp 0.913
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getMetadata() 0 10 1
B validate() 0 24 7
1
<?php declare(strict_types=1);
2
3
namespace Formularium\Validator;
4
5
use Formularium\Datatype;
6
use Formularium\Exception\ValidatorException;
7
use Formularium\Field;
8
use Formularium\Model;
9
use Formularium\ValidatorInterface;
10
use Formularium\ValidatorMetadata;
11
use Formularium\ValidatorArgs;
12
13
/**
14
 * The field under validation must be present and not empty only if all of the other specified fields are present.
15
 */
16
class RequiredWithAll implements ValidatorInterface
17
{
18 2
    public static function validate($value, array $options = [], Datatype $datatype, ?Model $model = null)
19
    {
20 2
        if (!$model) {
21
            throw new ValidatorException("RequiredWith needs a model");
22
        }
23
24 2
        $expectedFields = $options['fields'];
25 2
        if (!is_array($expectedFields)) {
26
            $expectedFields = [$expectedFields];
27
        }
28 2
        $found = true;
29 2
        $data = $model->getData();
30 2
        foreach ($expectedFields as $ef) {
31 2
            if (!array_key_exists($ef, $data)) {
32 1
                $found = false;
33 1
                break;
34
            }
35
        }
36
37 2
        if ($found && empty($value)) {
38 1
            throw new ValidatorException("Field is required when all fields " . implode(',', $expectedFields) . ' are present');
39
        }
40
41 1
        return $value;
42
    }
43
44 1
    public static function getMetadata(): ValidatorMetadata
45
    {
46 1
        return new ValidatorMetadata(
47 1
            'RequiredWithAll',
48 1
            "The field under validation must be present and not empty only if all of the other specified fields are present.",
49
            [
50 1
                new ValidatorArgs(
51 1
                    'fields',
52 1
                    '[String]',
53 1
                    'The fields that are required with'
54
                )
55
            ]
56
        );
57
    }
58
}
59