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

StringValidator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 90%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
lcom 1
cbo 6
dl 0
loc 43
ccs 9
cts 10
cp 0.9
rs 10
c 1
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 16 3
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