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

CountValidator::isValid()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 18
ccs 9
cts 10
cp 0.9
rs 9.2
c 1
b 0
f 0
cc 4
eloc 10
nc 4
nop 2
crap 4.016
1
<?php
2
3
namespace Maslosoft\Mangan\Validators\BuiltIn;
4
5
use Countable;
6
use Maslosoft\Addendum\Interfaces\AnnotatedInterface;
7
use Maslosoft\Mangan\Interfaces\Validators\ValidatorInterface;
8
use Maslosoft\Mangan\Meta\ManganMeta;
9
use Maslosoft\Mangan\Validators\BuiltIn\Base\SizeValidator;
10
use Maslosoft\Mangan\Validators\Traits\OnScenario;
11
use Maslosoft\Mangan\Validators\Traits\Safe;
12
use Maslosoft\Mangan\Validators\Traits\When;
13
14
/**
15
 * CountValidator
16
 *
17
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
18
 */
19
class CountValidator extends SizeValidator implements ValidatorInterface
20
{
21
22
	use OnScenario,
23
	  Safe,
24
	  When;
25
26
	/**
27
	 * @Label('There are not enough of {attribute} (minimum is {min})')
28
	 * @var string
29
	 */
30
	public $msgTooShort = '';
31
32
	/**
33
	 * @Label('There are too many of {attribute} (maximum is {max})')
34
	 * @var string
35
	 */
36
	public $msgTooLong = '';
37
38
	/**
39
	 * @Label('There must be exact {length} number of {attribute}')
40
	 * @var string
41
	 */
42
	public $msgLength = '';
43
44 8
	public function isValid(AnnotatedInterface $model, $attribute)
45
	{
46 8
		if (!$this->whenValidate($model))
47
		{
48
			return true;
49
		}
50 8
		$label = ManganMeta::create($model)->field($attribute)->label;
51 8
		if (!is_array($model->$attribute))
52
		{
53 2
			if (!$model->$attribute instanceof Countable)
54
			{
55 1
				$this->addError('msgInvalid', ['{attribute}' => $label]);
56 1
				return false;
57
			}
58
		}
59 7
		$value = count($model->$attribute);
60 7
		return $this->isValidValueOf($model, $attribute, $value, $label);
61
	}
62
63
}
64