Test Failed
Push — master ( 9608fc...ccdba4 )
by Jean-Christophe
07:46
created

LengthValidator::validateValue()   B

Complexity

Conditions 9
Paths 5

Size

Total Lines 17
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 27.878

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 17
ccs 5
cts 13
cp 0.3846
rs 8.0555
c 0
b 0
f 0
cc 9
nc 5
nop 1
crap 27.878
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 3
	protected $min;
19 3
	protected $max;
20 3
	protected $charset = "UTF-8";
21 3
22
	public function __construct() {
23
		parent::__construct ();
24
		$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
	}
26 3
27
	public function validate($value) {
28 3
		if (parent::validate ( $value ) === false) {
29 3
			return false;
30 1
		}
31
		if (! is_scalar ( $value ) && ! (\is_object ( $value ) && method_exists ( $value, '__toString' ))) {
32 3
			Logger::warn ( "Validation", "This value is not valid string for the charset " . $this->charset );
33 1
			return true;
34 1
		}
35
		return $this->validateValue ( ( string ) $value );
36 2
	}
37 2
38 2
	private function validateValue($stringValue) {
39 2
		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 2
				$this->violation = "exact";
43
				return false;
44
			} elseif ($this->max !== null && $length > $this->max) {
45 2
				$this->violation = "max";
46
				return false;
47
			} elseif ($this->min !== null && $length < $this->min) {
48
				$this->violation = "min";
49 2
				return false;
50
			}
51
			return true;
52
		} else {
53
			$this->violation = "charset";
54
			return false;
55
		}
56
	}
57
58
	/**
59
	 *
60 1
	 * {@inheritdoc}
61 1
	 * @see \Ubiquity\contents\validation\validators\Validator::getParameters()
62
	 */
63
	public function getParameters(): array {
64
		return [ "min","max","charset","value" ];
65
	}
66
}
67
68