Completed
Push — master ( 6fa4f0...1b5b15 )
by Lee
01:44
created

AbstractRegexValidator::isValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 10
cts 10
cp 1
rs 9.6666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Lavibi\Popoya;
4
5
abstract class AbstractRegexValidator extends AbstractValidator
6
{
7
    const NOT_STRING = 'not_string';
8
    const NOT_MATCH = 'not_match';
9
    const NOT_STRING_MESSAGE = 'The given value must be string.';
10
    const NOT_MATCH_MESSAGE = 'The given value is not match regex.';
11
12
    protected $messages = [
13
        self::NOT_STRING => self::NOT_STRING_MESSAGE,
14
        self::NOT_MATCH => self::NOT_MATCH_MESSAGE
15
    ];
16
17
    protected $requiredOptions = [
18
        'regex'
19
    ];
20
21
    protected $notMatchCode = self::NOT_MATCH;
22
23
    /**
24
     * @param $value
25
     * @return bool
26
     *
27
     * @throws Exception\MissingOptionException
28
     */
29 5
    public function isValid($value)
30
    {
31 5
        $this->value = $this->standardValue = $value;
32
33 5
        $this->checkMissingOptions();
34
35 4
        if (!is_string($value)) {
36 2
            $this->setError(self::NOT_STRING);
37 2
            return false;
38
        }
39
40 3
        if (!preg_match($this->options['regex'], $value)) {
41 2
            $this->setError($this->notMatchCode);
42 2
            return false;
43
        }
44
45 1
        return true;
46
    }
47
}
48