Validator.php
16.8 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
<?php
/**
* Created by PhpStorm.
* User: Zip
* Date: 15/4/19
* Time: 下午5:58
*/
namespace Hood\Helper\Validation;
use Hood\Core\Support\Str;
use Hood\Core\Support\Arr;
class Validator
{
private $files = array();
private $data;
protected $failedRules = array();
private $rules;
protected $numericRules = array('Numeric', 'Integer');
protected $implicitRules = array(
'Required'
);
protected $messagesRules = array(
'alphadash' => 'alpha_dash',
'alphanum' => 'alpha_num',
'digitsbetween' => 'digits_between',
'notin' => 'not_in',
'activeurl' => 'active_url'
);
/**
* @var Messages
*/
private $messages;
public function __construct(array $data, array $rules, array $customMessages = array())
{
$this->messages = new Messages($customMessages);
$this->data = $this->parseData($data);
$this->rules = $this->explodeRules($rules);
}
/**
* 自定义错误信息
* @param array $customMessages
* @return $this
*/
public function customMessages(array $customMessages = array())
{
$this->messages->customMessages($customMessages);
return $this;
}
/**
* 解析数据
* @param array $data
*/
protected function parseData(array $data)
{
$this->files = array();
foreach ($data as $key => $value) {
if ($value instanceof File) {
$this->files[$key] = $value;
unset($data[$key]);
}
}
return $data;
}
/**
* 拆分规则
* @param $rules
* @return mixed
*/
protected function explodeRules($rules)
{
foreach ($rules as $key => &$rule) {
$rule = (is_string($rule)) ? explode('|', $rule) : $rule;
}
return $rules;
}
/**
* 通过
* @return bool
*/
public function passes()
{
foreach ($this->rules as $attribute => $rules) {
foreach ($rules as $rule) {
$this->validate($attribute, $rule);
}
}
return count($this->messages->all()) === 0;
}
protected function doReplacements($message, $attribute, $rule, $parameters)
{
if (method_exists($this, $replacer = "replace{$rule}")) {
return $this->$replacer($message, $attribute, $rule, $parameters);
}
return '';
}
protected function validate($attribute, $rule)
{
list($rule, $parameters) = $this->parseRule($rule);
if ($rule == '') return;
$value = $this->getValue($attribute);
$validatable = $this->isValidatable($rule, $attribute, $value);
$method = "validate{$rule}";
if ($validatable && !$this->$method($attribute, $value, $parameters, $this)) {
$this->addError($attribute, $rule, $parameters, $value);
$this->failedRules[$attribute][$rule] = $parameters;
}
}
protected function addError($attribute, $rule, $parameters, $value)
{
$messagesKey = strtolower($rule);
if (isset($this->messagesRules[$messagesKey])) {
$messagesKey = $this->messagesRules[$messagesKey];
}
$message = $this->messages->getMessages($messagesKey, $this->getValueType($value));
$message = $this->doReplacements($message, $attribute, $rule, $parameters);
$this->messages->setMessages(strtolower($attribute), $message);
}
protected function getValueType($value)
{
if (is_numeric($value)) {
return 'numeric';
} elseif (is_array($value)) {
return 'array';
} elseif (is_string($value)) {
return 'string';
}
return null;
}
protected function getAttributeType($attribute)
{
if ($this->hasRule($attribute, $this->numericRules)) {
return 'numeric';
} elseif ($this->hasRule($attribute, array('Array'))) {
return 'array';
}
return 'string';
}
protected function getAttribute($attribute)
{
return str_replace('_', ' ', Str::snake($attribute));
}
protected function getSize($attribute, $value)
{
$hasNumeric = $this->hasRule($attribute, $this->numericRules);
if (is_numeric($value) && $hasNumeric) {
return $this->data[$attribute];
} elseif (is_array($value)) {
return count($value);
}
return $this->getStringSize($value);
}
protected function getStringSize($value)
{
if (function_exists('mb_strlen')) return mb_strlen($value);
return strlen($value);
}
protected function requireParameterCount($count, $parameters, $rule)
{
if (count($parameters) < $count) {
throw new \Exception("Validation rule $rule requires at least $count parameters.");
}
}
protected function isValidatable($rule, $attribute, $value)
{
return $this->presentOrRuleIsImplicit($rule, $attribute, $value) && $this->passesOptionalCheck($attribute);
}
protected function hasRule($attribute, $rules)
{
return !is_null($this->getRule($attribute, $rules));
}
protected function passesOptionalCheck($attribute)
{
if ($this->hasRule($attribute, array('Sometimes'))) {
return array_key_exists($attribute, $this->arrayDot($this->data))
|| array_key_exists($attribute, $this->files);
}
return true;
}
protected function arrayDot($array, $prepend = '')
{
$results = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$results = array_merge($results, $this->arrayDot($value, $prepend . $key . '.'));
} else {
$results[$prepend . $key] = $value;
}
}
return $results;
}
protected function getRule($attribute, $rules)
{
if (!array_key_exists($attribute, $this->rules)) {
return;
}
$rules = (array)$rules;
foreach ($this->rules[$attribute] as $rule) {
list($rule, $parameters) = $this->parseRule($rule);
if (in_array($rule, $rules)) return [$rule, $parameters];
}
}
protected function presentOrRuleIsImplicit($rule, $attribute, $value)
{
return $this->validateRequired($attribute, $value) || $this->isImplicit($rule);
}
protected function isImplicit($rule)
{
return in_array($rule, $this->implicitRules);
}
protected function getValue($attribute)
{
if (isset($this->data[$attribute])) {
return $this->data[$attribute];
} elseif (isset($this->files[$attribute])) {
return $this->files[$attribute];
}
}
protected function parseRule($rules)
{
if (is_array($rules)) {
return $this->parseArrayRule($rules);
}
return $this->parseStringRule($rules);
}
protected function parseArrayRule(array $rules)
{
return array(Str::studly(trim(array_get($rules, 0))), array_slice($rules, 1));
}
protected function parseStringRule($rules)
{
$parameters = [];
if (strpos($rules, ':') !== false) {
list($rules, $parameter) = explode(':', $rules, 2);
$parameters = $this->parseParameters($rules, $parameter);
}
return array(Str::studly(trim($rules)), $parameters);
}
protected function parseParameters($rule, $parameter)
{
if (strtolower($rule) == 'regex') return array($parameter);
return str_getcsv($parameter);
}
public function fails()
{
return !$this->passes();
}
protected function replaceString($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}'), $attribute, $message);
}
protected function validateString($attribute, $value)
{
return is_string($value);
}
protected function replaceRequired($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateRequired($attribute, $value)
{
if (is_null($value)) {
return false;
} elseif (is_string($value) && trim($value) === '') {
return false;
} elseif (is_array($value) && count($value) < 1) {
return false;
}
return true;
}
protected function replaceActiveUrl($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateActiveUrl($attribute, $value)
{
$url = str_replace(array('http://', 'https://', 'ftp://'), '', strtolower($value));
return checkdnsrr($url);
}
protected function validateUrl($attribute, $value)
{
return filter_var($value, FILTER_VALIDATE_URL) !== false;
}
protected function replaceUrl($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateAfter($attribute, $value)
{
return strtotime($value) ? true : false;
}
protected function replaceAfter($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{date}'), array($attribute, $parameters[0]), $message);
}
protected function validateAlpha($attribute, $value)
{
return preg_match('/^[\pL\pM]+$/u', $value);
}
protected function replaceAlpha($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateAlphaDash($attribute, $value)
{
return preg_match('/^[\pL\pM\pN_-]+$/u', $value);
}
protected function replaceAlphaDash($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateAlphaNum($attribute, $value)
{
return preg_match('/^[\pL\pM\pN]+$/u', $value);
}
protected function replaceAlphaNum($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateArray($attribute, $value)
{
return is_array($value);
}
protected function replaceArray($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateBetween($attribute, $value, $parameters)
{
$this->requireParameterCount(2, $parameters, 'between');
$size = $this->getSize($attribute, $value);
return $size >= $parameters[0] && $size <= $parameters[1];
}
protected function replaceBetween($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{min}', '{max}'), array_merge((array)$attribute, $parameters), $message);
}
protected function validateConfirmed($attribute, $value, $parameters)
{
return $this->validateSame($attribute, $value, $parameters);
}
protected function replaceConfirmed($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}'), $attribute, $message);
}
protected function validateSame($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'same');
$other = Arr::get($this->data, $parameters[0]);
return (isset($other) && $value == $other);
}
protected function replaceSame($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{other}'), array($attribute, $this->getAttribute($parameters[0])), $message);
}
protected function validateDate($attribute, $value)
{
if ($value instanceof DateTime) return true;
if (strtotime($value) === false) return false;
$date = date_parse($value);
return checkdate($date['month'], $date['day'], $date['year']);
}
protected function replaceDate($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateDigits($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'digits');
return $this->validateNumeric($attribute, $value) && strlen((string)$value) == $parameters[0];
}
protected function replaceDigits($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{digits}'), array($attribute, $parameters[0]), $message);
}
protected function validateDigitsBetween($attribute, $value, $parameters)
{
$this->requireParameterCount(2, $parameters, 'digits_between');
$length = strlen((string)$value);
return $length >= $parameters[0] && $length <= $parameters[1];
}
protected function replaceDigitsBetween($message, $attribute, $rule, $parameters)
{
return $this->replaceBetween($message, $attribute, $rule, $parameters);
}
protected function validateBoolean($attribute, $value)
{
$acceptable = array(true, false, 0, 1, '0', '1');
return in_array($value, $acceptable, true);
}
protected function replaceBoolean($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateEmail($attribute, $value)
{
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
}
protected function replaceEmail($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateIn($attribute, $value, $parameters)
{
return in_array((string)$value, $parameters);
}
protected function replaceIn($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{data}'), array($attribute, implode(',', $parameters)), $message);
}
protected function validateNotIn($attribute, $value, $parameters)
{
return !$this->validateIn($attribute, $value, $parameters);
}
protected function replaceNotIn($message, $attribute, $rule, $parameters)
{
return $this->replaceIn($message, $attribute, $rule, $parameters);
}
protected function validateInteger($attribute, $value)
{
return filter_var($value, FILTER_VALIDATE_INT) !== false;
}
protected function replaceInteger($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateIp($attribute, $value)
{
return filter_var($value, FILTER_VALIDATE_IP) !== false;
}
protected function replaceIp($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function replaceMax($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{max}'), array($attribute, $parameters[0]), $message);
}
protected function validateMax($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'max');
return $this->getSize($attribute, $value) <= $parameters[0];
}
protected function validateMin($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'min');
return $this->getSize($attribute, $value) >= $parameters[0];
}
protected function replaceMin($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{min}'), array($attribute, $parameters[0]), $message);
}
protected function validateNumeric($attribute, $value)
{
return is_numeric($value);
}
protected function replaceNumeric($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateRegex($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'regex');
return preg_match($parameters[0], $value);
}
protected function replaceRegex($message, $attribute, $rule, $parameters)
{
return str_replace('{attribute}', $attribute, $message);
}
protected function validateSize($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'size');
return $this->getSize($attribute, $value) == $parameters[0];
}
protected function replaceSize($message, $attribute, $rule, $parameters)
{
return str_replace(array('{attribute}', '{size}'), array($attribute, $parameters[0]), $message);
}
public function messages()
{
return $this->messages;
}
public function errors()
{
return $this->messages;
}
}