SameAs::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 1
Bugs 0 Features 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 1
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
 * May not be present, but if it is must not be empty.
15
 */
16
class SameAs implements ValidatorInterface
17
{
18 3
    public static function validate($value, array $options = [], ?Model $model = null)
19
    {
20 3
        if (!$model) {
21 1
            throw new ValidatorException('Same as requires a model.');
22
        }
23 2
        $modelData = $model->getData();
24
25 2
        $same = $options['target'];
26 2
        if (!array_key_exists($same, $modelData)) {
27
            throw new ValidatorException('Same as field not found.');
28
        }
29 2
        if ($modelData[$same] !== $value) {
30 1
            throw new ValidatorException('Field does not match ' . $same);
31
        }
32 1
        return $value;
33
    }
34
35 2
    public static function getMetadata(): Metadata
36
    {
37 2
        return new Metadata(
38 2
            'SameAs',
39 2
            "Must be the same as a target field.",
40
            [
41 2
                new MetadataParameter(
42 2
                    'target',
43 2
                    'String',
44 2
                    'Target field'
45
                )
46
            ]
47
        );
48
    }
49
}
50