Completed
Push — master ( 6bcea8...250c3f )
by Shcherbak
02:41
created

Regexp::isValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
crap 3.0261
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
      if ($this->regexp === null) {
53
        return true;
54
      }
55
56 1
      if (preg_match($this->regexp, $value)) {
57 1
        return true;
58
      }
59
60 1
      $this->addError($this->error);
61 1
      return false;
62
    }
63
64
  }