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

CountValidator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
c 1
b 0
f 0
lcom 0
cbo 5
dl 0
loc 40
ccs 0
cts 14
cp 0
rs 10

1 Method

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