1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ubiquity\contents\validation\validators\multiples; |
4
|
|
|
|
5
|
|
|
use Ubiquity\log\Logger; |
6
|
|
|
use Ubiquity\contents\validation\validators\HasNotNullInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Validate Strings length using min, max, charset,notNull parameters |
10
|
|
|
* Ubiquity\contents\validation\validators\multiples$LengthValidator |
11
|
|
|
* This class is part of Ubiquity |
12
|
|
|
* |
13
|
|
|
* @author jcheron <[email protected]> |
14
|
|
|
* @version 1.0.2 |
15
|
|
|
* |
16
|
|
|
*/ |
17
|
|
|
class LengthValidator extends ValidatorMultiple implements HasNotNullInterface { |
18
|
|
|
protected $min; |
19
|
|
|
protected $max; |
20
|
|
|
protected $charset = "UTF-8"; |
21
|
|
|
|
22
|
3 |
|
public function __construct() { |
23
|
3 |
|
parent::__construct (); |
24
|
3 |
|
$this->message = array_merge ( $this->message, [ "max" => "This value must be at least {min} characters long","min" => "This value cannot be longer than {max} characters","exact" => "This value should have exactly {min} characters.","charset" => "This value is not in {charset} charset" ] ); |
25
|
3 |
|
} |
26
|
|
|
|
27
|
3 |
|
public function validate($value) { |
28
|
3 |
|
if (parent::validate ( $value ) === false) { |
29
|
1 |
|
return false; |
30
|
|
|
} |
31
|
3 |
|
if (! is_scalar ( $value ) && ! (\is_object ( $value ) && method_exists ( $value, '__toString' ))) { |
32
|
1 |
|
Logger::warn ( "Validation", "This value is not valid string for the charset " . $this->charset ); |
33
|
1 |
|
return true; |
34
|
|
|
} |
35
|
2 |
|
return $this->validateValue ( ( string ) $value ); |
36
|
|
|
} |
37
|
|
|
|
38
|
2 |
|
private function validateValue($stringValue) { |
39
|
2 |
|
if (@mb_check_encoding ( $stringValue, $this->charset )) { |
40
|
2 |
|
$length = mb_strlen ( $stringValue, $this->charset ); |
41
|
2 |
|
if ($this->min === $this->max && $this->min !== null && $length !== $this->max) { |
42
|
|
|
$this->violation = "exact"; |
43
|
|
|
return false; |
44
|
2 |
|
} elseif ($this->max !== null && $length > $this->max) { |
45
|
|
|
$this->violation = "max"; |
46
|
|
|
return false; |
47
|
2 |
|
} elseif ($this->min !== null && $length < $this->min) { |
48
|
|
|
$this->violation = "min"; |
49
|
|
|
return false; |
50
|
|
|
} |
51
|
2 |
|
return true; |
52
|
|
|
} else { |
53
|
|
|
$this->violation = "charset"; |
54
|
|
|
return false; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* |
60
|
|
|
* {@inheritdoc} |
61
|
|
|
* @see \Ubiquity\contents\validation\validators\Validator::getParameters() |
62
|
|
|
*/ |
63
|
1 |
|
public function getParameters(): array { |
64
|
1 |
|
return [ "min","max","charset","value" ]; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
|