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

CountValidator::isValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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