Completed
Push — master ( 587f5e...7e0186 )
by Jean-Christophe
04:40
created

LengthValidator::getParameters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 2
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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
 * @author jc
11
 */
12
class LengthValidator extends ValidatorMultiple implements HasNotNullInterface{
13
	
14
	protected $min;
15
	protected $max;
16
	protected $charset="UTF-8";
17
	
18 1
	public function __construct(){
19 1
		parent::__construct();
20 1
		$this->message=array_merge($this->message,[
21 1
				"max"=>"This value must be at least {min} characters long",
22
				"min"=>"This value cannot be longer than {max} characters",
23
				"exact"=>"This value should have exactly {min} characters.",
24
				"charset"=>"This value is not in {charset} charset"
25
		]);
26 1
	}
27
	
28 1
	public function validate($value) {
29 1
		if(parent::validate($value)===false){
30 1
			return false;
31
		}
32 1
		if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
33 1
			Logger::warn("Validation", "This value is not valid string for the charset ".$this->charset);
34 1
			return true;
35
		}
36
		$stringValue = (string) $value;
37
		if (@mb_check_encoding($stringValue, $this->charset)) {
38
			$length = mb_strlen($stringValue, $this->charset);
39
			if($this->min===$this->max && $this->min!==null && $length!==$this->max){
40
				$this->violation="exact";
41
				return false;
42
			}elseif($this->max!==null && $length>$this->max){
43
				$this->violation="max";
44
				return false;
45
			}elseif($this->min!==null && $length<$this->min){
46
				$this->violation="min";
47
				return false;
48
			}
49
			return true;
50
		}else{
51
			$this->violation="charset";
52
			return false;
53
		}
54
	}
55
	
56
	/**
57
	 * {@inheritDoc}
58
	 * @see \Ubiquity\contents\validation\validators\Validator::getParameters()
59
	 */
60 1
	public function getParameters(): array {
61 1
		return ["min","max","charset","value"];
62
	}
63
64
}
65
66