Completed
Push — master ( 94ddbb...e5219e )
by Jean-Christophe
04:25
created

LengthValidator   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 71.43%

Importance

Changes 0
Metric Value
wmc 15
eloc 32
dl 0
loc 50
ccs 20
cts 28
cp 0.7143
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getParameters() 0 2 1
A __construct() 0 7 1
C validate() 0 25 13
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 3
	public function __construct(){
19 3
		parent::__construct();
20 3
		$this->message=array_merge($this->message,[
21 3
				"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 3
	}
27
	
28 3
	public function validate($value) {
29 3
		if(parent::validate($value)===false){
30 1
			return false;
31
		}
32 3
		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 2
		$stringValue = (string) $value;
37 2
		if (@mb_check_encoding($stringValue, $this->charset)) {
38 2
			$length = mb_strlen($stringValue, $this->charset);
39 2
			if($this->min===$this->max && $this->min!==null && $length!==$this->max){
40
				$this->violation="exact";
41
				return false;
42 2
			}elseif($this->max!==null && $length>$this->max){
43
				$this->violation="max";
44
				return false;
45 2
			}elseif($this->min!==null && $length<$this->min){
46
				$this->violation="min";
47
				return false;
48
			}
49 2
			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