Completed
Push — master ( e0f179...77291c )
by Peter
06:24
created

StringValidator::isValid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0625

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
ccs 6
cts 8
cp 0.75
rs 9.4285
cc 2
eloc 8
nc 2
nop 2
crap 2.0625
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
23
/**
24
 * StringValidator
25
 *
26
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
27
 */
28
class StringValidator extends SizeValidator implements ValidatorInterface
29
{
30
31
	use OnScenario,
32
	  Safe;
33
34
	/**
35
	 * @Label('{attribute} is too short (minimum is {min} characters)')
36
	 * @var string
37
	 */
38
	public $msgTooShort = '';
39
40
	/**
41
	 * @Label('{attribute} is too long (maximum is {max} characters)')
42
	 * @var string
43
	 */
44
	public $msgTooLong = '';
45
46
	/**
47
	 * @Label('{attribute} is of the wrong length (should be {length} characters)')
48
	 * @var string
49
	 */
50
	public $msgLength = '';
51
52 6
	public function isValid(AnnotatedInterface $model, $attribute)
53
	{
54 6
		$label = ManganMeta::create($model)->field($attribute)->label;
55 6
		$value = $model->$attribute;
56 6
		if (!is_string($value))
57
		{
58
			$this->addError('msgInvalid', ['{attribute}' => $label]);
59
			return false;
60
		}
61 6
		$length = mb_strlen($value);
62 6
		return $this->isValidValueOf($model, $attribute, $length, $label);
63
	}
64
65
}
66