Completed
Pull Request — 1.x (#5)
by Dorian
01:32
created

EnumValidator::validate()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.2
c 0
b 0
f 0
cc 4
eloc 3
nc 2
nop 2
1
<?php
2
namespace MetaHydrator\Validator;
3
4
use MetaHydrator\Exception\ValidationException;
5
6
/**
7
 * An implementation of ValidatorInterface used to limit allowed values to a list
8
 */
9
class EnumValidator extends AbstractValidator
10
{
11
    /** @var string[] */
12
    private $values;
13
    public function getValues() { return $this->values; }
14
    public function setValues(array $values) { $this->values = $values; }
15
    public function addValue(string $value) { $this->values[] = $value; }
16
17
    /**
18
     * EnumValidator constructor.
19
     * @param string[] $values
20
     * @param string $errorMessage
21
     */
22
    public function __construct(array $values, $errorMessage = "")
23
    {
24
        parent::__construct($errorMessage);
25
        $this->values = $values;
26
    }
27
28
    /**
29
     * @param mixed $value
30
     * @param $contextObject
31
     *
32
     * @throws ValidationException
33
     */
34
    public function validate($value, $contextObject = null)
35
    {
36
        if ($value !== null && $value !== '' && !in_array($value, $this->values)) {
37
            $this->throw();
38
        }
39
    }
40
}
41