-
Notifications
You must be signed in to change notification settings - Fork 0
/
TinyValidator.php
72 lines (63 loc) · 1.82 KB
/
TinyValidator.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
<?php
namespace TinyLara\TinyValidator;
class TinyValidator {
public $success = true;
public $errors = [];
private $reasons = [];
private $data;
private $rules;
public function __construct($data, $rules)
{
$this->data = $data;
$this->rules = $rules;
$this->reasons = require __DIR__.'/reasons.php';
$this->fire();
}
public function fire()
{
foreach ($this->rules as $attribute => $rule) {
foreach (explode('|', $rule) as $item) {
$detial = explode(':', $item);
if ( count( $detial ) > 1 ) {
$reason = $this->$detial[0]($this->data[$attribute], $detial[1]);
} else {
$reason = $this->$item($this->data[$attribute]);
}
if ( $reason !== true ) {
$this->errors[] = str_replace(':attribute', $attribute, $reason);
}
}
}
if ( count($this->errors) ) {
$this->success = false;
}
}
protected function required($value)
{
return !$value ? $this->reasons['required'] : true;
}
protected function email($value)
{
return filter_var($value, FILTER_VALIDATE_EMAIL) ? true : $this->reasons['email'];
}
protected function min($value, $min)
{
return mb_strlen($value, 'UTF-8') >= $min ? true : str_replace(':min', $min, $this->reasons['min']);
}
protected function max($value, $max)
{
return mb_strlen($value, 'UTF-8') <= $max ? true : str_replace(':max', $max, $this->reasons['max']);
}
protected function numeric($value)
{
return is_numeric($value) ? true : $this->reasons['numeric'];
}
protected function integer($value)
{
return filter_var($value, FILTER_VALIDATE_INT) !== false ? true : $this->reasons['integer'];
}
public function __call($method, $parameters)
{
throw new \UnexpectedValueException("Validate rule [$method] does not exist!");
}
}