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

CountValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 90%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
lcom 1
cbo 6
dl 0
loc 45
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 18 4
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