Passed
Push — master ( 5c767a...47de24 )
by Jean-Christophe
06:45
created

FieldValidation::setDepends()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
namespace Ajax\semantic\components\validation;
3
use Ajax\JsUtils;
4
use Ajax\service\JArray;
5
6
/**
7
 * @author jc
8
 * @version 1.001
9
 * Generates a JSON field validator
10
 */
11
class FieldValidation implements \JsonSerializable{
12
	/**
13
	 * @var string
14
	 */
15
	protected  $identifier;
16
	/**
17
	 * @var array array of Rules
18
	 */
19
	protected $rules;
20
	/**
21
	 * @var array array of custom rules
22
	 */
23
	protected $customRules;
24
25
	protected $hasCustomRules=false;
26
27
	/**
28
	 * @var string
29
	 */
30
	protected $depends;
31
32
	protected $optional;
33
34
	public function __construct($identifier){
35
		$this->identifier=$identifier;
36
		$this->rules=[];
37
	}
38
39
	public function getIdentifier() {
40
		return $this->identifier;
41
	}
42
43
	public function setIdentifier($identifier) {
44
		$this->identifier=$identifier;
45
		return $this;
46
	}
47
48
	public function getRules() {
49
		return $this->rules;
50
	}
51
52
	/**
53
	 * @param string|Rule|array $type
54
	 * @param string $prompt
55
	 * @param string $value
56
	 * @return Rule
57
	 */
58
	public function addRule($type,$prompt=NULL,$value=NULL){
59
		if($type instanceof  Rule) {
60
			$rule = $type;
61
			if($type instanceof CustomRule){
62
				$this->customRules[]=$type;
63
				$this->hasCustomRules=true;
64
			}
65
		}elseif(\is_array($type)){
66
			$value=JArray::getValue($type, "value", 2);
67
			$prompt=JArray::getValue($type, "prompt", 1);
68
			$type=JArray::getValue($type, "type", 0);
69
			$rule=new Rule($type,$prompt,$value);
70
		}else {
71
			$rule = new Rule($type, $prompt, $value);
72
		}
73
		$this->rules[]=$rule;
74
		return $rule;
75
	}
76
77
	public function jsonSerialize(){
78
		$result=["identifier"=>$this->identifier,"rules"=>$this->rules];
79
		if($this->optional){
80
			$result["optional"]=true;
81
		}
82
		if(isset($this->depends)){
83
			$result["depends"]=$this->depends;
84
		}
85
		return $result;
86
	}
87
88
	public function setDepends($depends) {
89
		$this->depends=$depends;
90
		return $this;
91
	}
92
93
	public function setOptional($optional) {
94
		$this->optional=$optional;
95
		return $this;
96
	}
97
98
	public function compile(JsUtils $js){
99
		if($this->hasCustomRules) {
100
			foreach ($this->customRules as $rule) {
101
				$rule->compile($js);
102
			}
103
		}
104
	}
105
106
}
107