RequiredWith::getMetadata()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 10
ccs 8
cts 8
cp 1
crap 1
rs 10
c 0
b 0
f 0
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\Metadata;
11
use Formularium\MetadataParameter;
12
13
/**
14
 * The field under validation must be present and not empty only if any of the other specified fields are present.
15
 */
16
class RequiredWith implements ValidatorInterface
17
{
18 2
    public static function validate($value, array $options = [], ?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
        $found = false;
26 2
        $data = $model->getData();
27 2
        foreach ($expectedFields as $ef) {
28 2
            if (array_key_exists($ef, $data) && !empty($data[$ef])) {
29 2
                $found = true;
30 2
                break;
31
            }
32
        }
33 2
        if ($found && empty($value)) {
34 1
            throw new ValidatorException("Field is required when at least one of fields " . implode(',', $expectedFields) . ' are present');
35
        }
36 1
        return $value;
37
    }
38
39 1
    public static function getMetadata(): Metadata
40
    {
41 1
        return new Metadata(
42 1
            'RequiredWith',
43 1
            "The field under validation must be present and not empty only if any of the other specified fields are present.",
44
            [
45 1
                new MetadataParameter(
46 1
                    'fields',
47 1
                    '[String]',
48 1
                    'The fields that are required with'
49
                )
50
            ]
51
        );
52
    }
53
}
54