Completed
Push — master ( 77291c...632b2b )
by Peter
06:20
created

StringValidator::isValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 10
cp 0.9
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 2
crap 3.009
1
<?php
2
3
/**
4
 * This software package is licensed under AGPL or Commercial license.
5
 *
6
 * @package maslosoft/mangan
7
 * @licence AGPL or Commercial
8
 * @copyright Copyright (c) Piotr Masełkowski <[email protected]>
9
 * @copyright Copyright (c) Maslosoft
10
 * @copyright Copyright (c) Others as mentioned in code
11
 * @link https://maslosoft.com/mangan/
12
 */
13
14
namespace Maslosoft\Mangan\Validators\BuiltIn;
15
16
use Maslosoft\Addendum\Interfaces\AnnotatedInterface;
17
use Maslosoft\Mangan\Interfaces\Validators\ValidatorInterface;
18
use Maslosoft\Mangan\Meta\ManganMeta;
19
use Maslosoft\Mangan\Validators\BuiltIn\Base\SizeValidator;
20
use Maslosoft\Mangan\Validators\Traits\OnScenario;
21
use Maslosoft\Mangan\Validators\Traits\Safe;
22
use Maslosoft\Mangan\Validators\Traits\When;
23
24
/**
25
 * StringValidator
26
 *
27
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
28
 */
29
class StringValidator extends SizeValidator implements ValidatorInterface
30
{
31
32
	use OnScenario,
33
	  Safe,
34
	  When;
35
36
	/**
37
	 * @Label('{attribute} is too short (minimum is {min} characters)')
38
	 * @var string
39
	 */
40
	public $msgTooShort = '';
41
42
	/**
43
	 * @Label('{attribute} is too long (maximum is {max} characters)')
44
	 * @var string
45
	 */
46
	public $msgTooLong = '';
47
48
	/**
49
	 * @Label('{attribute} is of the wrong length (should be {length} characters)')
50
	 * @var string
51
	 */
52
	public $msgLength = '';
53
54 7
	public function isValid(AnnotatedInterface $model, $attribute)
55
	{
56 7
		if (!$this->whenValidate($model))
57
		{
58
			return true;
59
		}
60 7
		$label = ManganMeta::create($model)->field($attribute)->label;
61 7
		$value = $model->$attribute;
62 7
		if (!is_string($value))
63
		{
64 1
			$this->addError('msgInvalid', ['{attribute}' => $label]);
65 1
			return false;
66
		}
67 6
		$length = mb_strlen($value);
68 6
		return $this->isValidValueOf($model, $attribute, $length, $label);
69
	}
70
71
}
72