Regexp::isValid()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
ccs 0
cts 11
cp 0
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 12
1
<?php
2
3
  namespace Fiv\Form\Validator;
4
5
  /**
6
   * @author Ivan Shcherbak <[email protected]>
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
    public function setRegexp($regexp) {
27
      if (!is_string($regexp)) {
28
        throw new \InvalidArgumentException('Invalid regexp type. Expect string');
29
      }
30
      $this->regexp = $regexp;
31
      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
    public function isValid($value) {
52
      $this->errors = [];
53
54
      if ($this->regexp === null) {
55
        return true;
56
      }
57
58
      if (preg_match($this->regexp, $value)) {
59
        return true;
60
      }
61
62
      $this->addError($this->error);
63
      return false;
64
    }
65
66
  }