|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ubiquity\contents\validation\validators\multiples; |
|
4
|
|
|
|
|
5
|
|
|
use Ubiquity\log\Logger; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Validate Strings length using min, max, charset,notNull parameters |
|
9
|
|
|
* @author jc |
|
10
|
|
|
*/ |
|
11
|
|
|
class LengthValidator extends ValidatorMultipleNotNull { |
|
12
|
|
|
|
|
13
|
|
|
protected $min; |
|
14
|
|
|
protected $max; |
|
15
|
|
|
protected $charset="UTF-8"; |
|
16
|
|
|
|
|
17
|
|
|
public function __construct(){ |
|
18
|
|
|
parent::__construct(); |
|
19
|
|
|
$this->message=array_merge($this->message,[ |
|
20
|
|
|
"max"=>"This value must be at least {min} characters long", |
|
21
|
|
|
"min"=>"This value cannot be longer than {max} characters", |
|
22
|
|
|
"exact"=>"This value should have exactly {min} characters.", |
|
23
|
|
|
"charset"=>"This value is not in {charset} charset" |
|
24
|
|
|
]); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function validate($value) { |
|
28
|
|
|
if(parent::validate($value)===false){ |
|
29
|
|
|
return false; |
|
30
|
|
|
} |
|
31
|
|
|
if (null === $value || '' === $value) { |
|
32
|
|
|
return true; |
|
33
|
|
|
} |
|
34
|
|
|
if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) { |
|
35
|
|
|
Logger::warn("Validation", "This value is not valid string for the charset ".$this->charset); |
|
36
|
|
|
return true; |
|
37
|
|
|
} |
|
38
|
|
|
$stringValue = (string) $value; |
|
39
|
|
|
if (@mb_check_encoding($stringValue, $this->charset)) { |
|
40
|
|
|
$length = mb_strlen($stringValue, $this->charset); |
|
41
|
|
|
if($this->min===$this->max && $this->min!==null && $length!==$this->max){ |
|
42
|
|
|
$this->violation="exact"; |
|
43
|
|
|
return false; |
|
44
|
|
|
}elseif($this->max!==null && $length>$this->max){ |
|
45
|
|
|
$this->violation="max"; |
|
46
|
|
|
return false; |
|
47
|
|
|
}elseif($this->min!==null && $length<$this->min){ |
|
48
|
|
|
$this->violation="min"; |
|
49
|
|
|
return false; |
|
50
|
|
|
} |
|
51
|
|
|
return true; |
|
52
|
|
|
}else{ |
|
53
|
|
|
$this->violation="charset"; |
|
54
|
|
|
return false; |
|
55
|
|
|
} |
|
56
|
|
|
return false; |
|
|
|
|
|
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* {@inheritDoc} |
|
61
|
|
|
* @see \Ubiquity\contents\validation\validators\Validator::getParameters() |
|
62
|
|
|
*/ |
|
63
|
|
|
public function getParameters(): array { |
|
64
|
|
|
return ["min","max","charset","value"]; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
|
This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.
Unreachable code is most often the result of
return,dieorexitstatements that have been added for debug purposes.In the above example, the last
return falsewill never be executed, because a return statement has already been met in every possible execution path.