Completed
Pull Request — master (#101)
by Marcio
02:15
created

Enum::validate()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6.0073

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 6
eloc 15
c 2
b 1
f 0
nc 4
nop 3
dl 0
loc 24
ccs 16
cts 17
cp 0.9412
crap 6.0073
rs 8.5125
1
<?php
2
3
namespace League\JsonGuard\Constraints;
4
5
use League\JsonGuard\Assert;
6
use League\JsonGuard\ValidationError;
7
use League\JsonGuard\Validator;
8
9
class Enum implements Constraint
10
{
11
    const KEYWORD = 'enum';
12
13
    /**
14
     * {@inheritdoc}
15
     */
16 12
    public function validate($value, $parameter, Validator $validator)
17
    {
18 12
        Assert::type($parameter, 'array', self::KEYWORD, $validator->getPointer());
19
20 8
        if (is_object($value)) {
21 4
            foreach ($parameter as $i) {
22 4
                if (is_object($i) && $value == $i) {
23
                    return null;
24
                }
25 4
            }
26 4
        } else {
27 8
            if (in_array($value, $parameter, true)) {
28 8
                return null;
29
            }
30
        }
31
32 8
        return new ValidationError(
33 8
            'Value {value} is not one of: {choices}',
34 8
            self::KEYWORD,
35 8
            $value,
36 8
            $validator->getPointer(),
37 8
            ['choices' => $parameter, 'value' => $value]
38 8
        );
39
    }
40
}
41