Completed
Push — master ( 15d409...38a590 )
by Shcherbak
05:57 queued 13s
created

Len::max()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 5
rs 9.4285
c 1
b 0
f 0
ccs 4
cts 4
cp 1
cc 1
eloc 4
nc 1
nop 2
crap 1
1
<?php
2
3
  namespace Fiv\Form\Validator;
4
5
  /**
6
   * Check value length
7
   *
8
   * @author  Ivan Shcherbak <[email protected]>
9
   * @package Fiv\Form\Validator
10
   */
11
  class Len extends \Fiv\Form\Validator\Base {
12
13
    /**
14
     * @var int|null
15
     */
16
    protected $exactLen;
17
18
    /**
19
     * @var string|null
20
     */
21
    protected $exactLenError;
22
23
24
    /**
25
     * @var int|null
26
     */
27
    protected $minLen;
28
29
    /**
30
     * @var string|null
31
     */
32
    protected $minLenError;
33
34
35
    /**
36
     * @var int|null
37
     */
38
    protected $maxLen;
39
40
    /**
41
     * @var string|null
42
     */
43
    protected $maxLenError;
44
45
46
    /**
47
     * Maximum len of value
48
     *
49
     * @param $len
50
     * @param $error
51
     * @return $this
52
     */
53 1
    public function max($len, $error) {
54 1
      $this->maxLen = $len;
55 1
      $this->maxLenError = $error;
56 1
      return $this;
57
    }
58
59
60
    /**
61
     * Minimum len of value
62
     *
63
     * @param $len
64
     * @param $error
65
     * @return $this
66
     */
67 1
    public function min($len, $error) {
68 1
      $this->minLen = $len;
69 1
      $this->minLenError = $error;
70 1
      return $this;
71
    }
72
73
74
    /**
75
     * Expect exact len of value
76
     *
77
     * @param $len
78
     * @param $error
79
     * @return $this
80
     */
81
    public function exact($len, $error) {
82
      $this->exactLen = $len;
83
      $this->exactLenError = $error;
84
      return $this;
85
    }
86
87
88
    /**
89
     * Validate value
90
     * @param string $value
91
     * @return bool
92
     */
93 1
    public function isValid($value) {
94
95 1
      if ($this->exactLen !== null and mb_strlen($value, 'UTF-8') != $this->exactLen) {
96
        $this->addError(vsprintf($this->exactLenError, [$this->exactLen]));
97
      }
98
99 1
      if ($this->maxLen !== null and mb_strlen($value, 'UTF-8') > $this->maxLen) {
100 1
        $this->addError(vsprintf($this->maxLenError, [$this->maxLen]));
101
      }
102
103 1
      if ($this->minLen !== null and mb_strlen($value, 'UTF-8') < $this->minLen) {
104 1
        $this->addError(vsprintf($this->minLenError, [$this->minLen]));
105
      }
106
107 1
      return !$this->hasErrors();
108
    }
109
110
  }