forked from joostvanveen/php-oop-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidator.php
110 lines (95 loc) · 2.9 KB
/
Validator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
class Validator
{
/**
* Validation errors
* @var array
*/
private $errors = array();
/**
* Validate data against a set of rules and set errors in the $this->errors
* array
* @param array $data
* @param array $rules
* @return boolean
*/
public function validate (Array $data, Array $rules)
{
$valid = true;
foreach ($rules as $item => $ruleset) {
// required|email|min:8
$ruleset = explode('|', $ruleset);
foreach ($ruleset as $rule) {
$pos = strpos($rule, ':');
if ($pos !== false) {
$parameter = substr($rule, $pos + 1);
$rule = substr($rule, 0, $pos);
}
else {
$parameter = '';
}
// validateEmail($item, $value, $param)
$methodName = 'validate' . ucfirst($rule);
$value = isset($data[$item]) ? $data[$item] : NULL;
if (method_exists($this, $methodName)) {
$this->$methodName($item, $value, $parameter) OR $valid = false;
}
}
}
return $valid;
}
/**
* Get validation errors
* @return array:
*/
public function getErrors ()
{
return $this->errors;
}
/**
* Validate the $value of $item to see if it is present and not empty
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateRequired ($item, $value, $parameter)
{
if ($value === '' || $value === NULL) {
$this->errors[$item][] = 'The ' . $item . ' field is required';
return false;
}
return true;
}
/**
* Validate the $value of $item to see if it is a valid email address
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateEmail ($item, $value, $parameter)
{
if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->errors[$item][] = 'The ' . $item . ' field should be a valid email addres';
return false;
}
return true;
}
/**
* Validate the $value of $item to see if it is fo at least $param
* characters long
* @param string $item
* @param string $value
* @param string $parameter
* @return boolean
*/
private function validateMin ($item, $value, $parameter)
{
if (strlen($value) >= $parameter == false) {
$this->errors[$item][] = 'The ' . $item . ' field should have a minimum length of ' . $parameter;
return false;
}
return true;
}
}