Completed
Pull Request — master (#31)
by Vitaliy
02:53
created

Regexp::isValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 4
Bugs 1 Features 2
Metric Value
c 4
b 1
f 2
dl 0
loc 14
ccs 7
cts 8
cp 0.875
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 3.0175
1
<?php
2
3
  namespace Fiv\Form\Validator;
4
5
  /**
6
   * @author Ivan Shcherbak <[email protected]> 7/11/14
7
   */
8
  class Regexp extends BaseValidator {
9
10
    /**
11
     * @var string
12
     */
13
    protected $error = 'Invalid value';
14
15
    /**
16
     * @var string|null
17
     */
18
    protected $regexp = null;
19
20
21
    /**
22
     * @param string $regexp
23
     * @return $this
24
     * @throws \InvalidArgumentException
25
     */
26 1
    public function setRegexp($regexp) {
27 1
      if (!is_string($regexp)) {
28
        throw new \InvalidArgumentException('Invalid regexp type. Expect string');
29
      }
30 1
      $this->regexp = $regexp;
31 1
      return $this;
32
    }
33
34
35
    /**
36
     * @param string $error
37
     * @return $this
38
     */
39
    public function setError($error) {
40
      $this->error = $error;
41
      return $this;
42
    }
43
44
45
    /**
46
     * @todo check if we can pass array
47
     *
48
     * @param string $value
49
     * @return bool
50
     */
51 1
    public function isValid($value) {
52 1
      $this->flushErrors();
53
      
54 1
      if ($this->regexp === null) {
55
        return true;
56
      }
57
58 1
      if (preg_match($this->regexp, $value)) {
59 1
        return true;
60
      }
61
62 1
      $this->addError($this->error);
63 1
      return false;
64
    }
65
66
  }