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

When   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 0
loc 56
ccs 13
cts 13
cp 1
rs 10
c 1
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B whenValidate() 0 25 6
1
<?php
2
3
/*
4
 * To change this license header, choose License Headers in Project Properties.
5
 * To change this template file, choose Tools | Templates
6
 * and open the template in the editor.
7
 */
8
9
namespace Maslosoft\Mangan\Validators\Traits;
10
11
/**
12
 * Validate when criteria is met.
13
 *
14
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
15
 */
16
trait When
17
{
18
19
	/**
20
	 * Set this to string - to check if property value is trueish:
21
	 *
22
	 * ```
23
	 * $when = 'myProperty';
24
	 * ```
25
	 *
26
	 * This will check if property value is not `false` and validate
27
	 * only if this property is trueish.
28
	 *
29
	 * Set this to array to check specified criteria:
30
	 *
31
	 * ```
32
	 * $when = [
33
	 * 		'firstProperty' => 1,
34
	 * 		'secondProperty' => true
35
	 * ];
36
	 * ```
37
	 *
38
	 * Will run validation only when those values of model properties
39
	 * are exact as provided.
40
	 *
41
	 * @var string|array
42
	 */
43
	public $when = null;
44
45 36
	public function whenValidate($model)
46
	{
47 36
		if (empty($this->when))
48
		{
49 34
			return true;
50
		}
51 2
		if (is_string($this->when))
52
		{
53 1
			$name = $this->when;
54 1
			if ($model->$name)
55
			{
56 1
				return true;
57
			}
58
		}
59 1
		elseif (is_array($this->when))
60
		{
61 1
			$conditions = [];
62 1
			foreach ($this->when as $name => $value)
63
			{
64 1
				$conditions[] = $model->$name === $value;
65
			}
66 1
			return count($conditions) === array_sum($conditions);
67
		}
68 1
		return false;
69
	}
70
71
}
72