/
Validator.php
555 lines (483 loc) · 11.4 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
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
<?php
/**
* @package Fuel\Validation
* @version 2.0
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2013 Fuel Development Team
* @link http://fuelphp.com
*/
namespace Fuel\Validation;
use InvalidArgumentException;
use LogicException;
/**
* Main entry point for the validation functionality. Handles registering validation rules and loading validation
* adaptors.
*
* @package Fuel\Validation
* @author Fuel Development Team
* @since 2.0
*
* @method $this email()
* @method $this ip()
* @method $this matchField(string $matchAgainst)
* @method $this minLength(integer $minLength)
* @method $this maxLength(integer $maxLength)
* @method $this number()
* @method $this numericBetween([integer $min, integer $max])
* @method $this numericMax(integer $max)
* @method $this numericMin(integer $min)
* @method $this regex(string $regex)
* @method $this required()
* @method $this url()
* @method $this date(['format' => string $format])
* @method $this type(string $type)
* @method $this enum(array $values)
* @method $this enumMulti(array $values)
* @method $this validator(ValidatableInterface $validator)
*/
class Validator implements ValidatableInterface
{
/**
* Contains a list of fields to be validated
*
* @var FieldInterface[]
*/
protected $fields = array();
/**
* Contains a list of any custom validation rules
*
* @var string[]
*/
protected $customRules = array();
/**
* @var string[]
*/
protected $messages = array();
/**
* Keeps track of the last field added for magic method chaining
*
* @var FieldInterface
*/
protected $lastAddedField;
/**
* Keeps track of the last rule added for message setting
*
* @var RuleInterface
*/
protected $lastAddedRule;
/**
* Default namespace to look for rules in when a rule is not known
*
* @var string
*/
protected $ruleNamespace = 'Fuel\Validation\Rule\\';
/**
* Adds a rule that can be used to validate a field
*
* @param string|FieldInterface $field
* @param RuleInterface $rule
*
* @return $this
*
* @since 2.0
*/
public function addRule($field, RuleInterface $rule)
{
if (is_string($field))
{
try
{
$field = $this->getField($field);
}
catch (InvalidFieldException $ife)
{
// The field does not exist so create it
$this->addField($field);
$field = $this->getField($field);
}
}
// We have a valid field now so add the rule
$field->addRule($rule);
$this->lastAddedRule = $rule;
return $this;
}
/**
* Adds a new field to the validation object
*
* @param string|FieldInterface $field
* @param string $label Field name to use in messages, set to null to use $field
*
* @return $this
*
* @throws InvalidArgumentException
*
* @since 2.0
*/
public function addField($field, $label = null)
{
if (is_string($field))
{
$field = new Field($field, $label);
}
if ( ! $field instanceof FieldInterface)
{
throw new InvalidArgumentException('VAL-007: Only FieldInterfaces can be added as a field.');
}
$this->fields[$field->getName()] = $field;
$this->lastAddedField = $field;
return $this;
}
/**
* Returns the given field
*
* @param $name
*
* @return FieldInterface
*
* @throws InvalidFieldException
*
* @since 2.0
*/
public function getField($name)
{
if ( ! isset($this->fields[$name]))
{
throw new InvalidFieldException($name);
}
return $this->fields[$name];
}
/**
* Takes an array of data and validates that against the assigned rules.
* The array is expected to have keys named after fields.
* This function will call reset() before it runs.
*
* @param array $data
* @param ResultInterface $result
*
* @return ResultInterface
*
* @since 2.0
*/
public function run($data, ResultInterface $result = null)
{
if ($result === null)
{
$result = new Result;
}
$result->setResult(true);
foreach ($this->fields as $fieldName => $rules)
{
$fieldResult = $this->validateField($fieldName, $data, $result);
if ( ! $fieldResult)
{
// There was a failure so log it to the result object
$result->setResult(false);
}
}
return $result;
}
/**
* Takes a field name and an array of data and validates the field against the assigned rules.
* The array is expected to have keys named after fields.
* This function will call reset() before it runs.
*
* @param string $field
* @param array $data
* @param ResultInterface $result
*
* @return ResultInterface
*
* @since 2.0
*/
public function runField($field, array $data, ResultInterface $result = null)
{
if ($result === null)
{
$result = new Result;
}
$fieldResult = false;
if (isset($data[$field]))
{
$fieldResult = $this->validateField($field, $data, $result);
}
// Log the result
$result->setResult($fieldResult);
return $result;
}
/**
* Validates a single field
*
* @param string $field
* @param mixed[] $data
* @param ResultInterface $result
*
* @return bool
*
* @since 2.0
*/
protected function validateField($field, $data, ResultInterface $result)
{
$value = null;
// If there is data, and the data is not empty and not numeric. This allows for strings such as '0' to be passed
// as valid values.
$dataPresent = isset($data[$field]) && ! (empty($data[$field]) && ! is_numeric($data[$field]));
if ($dataPresent)
{
$value = $data[$field];
}
$rules = $this->getFieldRules($field);
foreach ($rules as $rule)
{
if ( ! $dataPresent && ! $rule->canAlwaysRun())
{
continue;
}
$validateResult = $rule->validate($value, $field, $data);
if ($validateResult instanceof ResultInterface)
{
$result->merge($validateResult, $field . '.');
return $validateResult->isValid();
}
if ( ! $validateResult)
{
// Don't allow any others to run if this one failed
$result->setError($field, $this->buildMessage($this->getField($field), $rule, $value), $rule);
return false;
}
}
// All is good so make sure the field gets added as one of the validated fields
$result->setValidated($field);
return true;
}
/**
* Gets a Rule's message and processes that with various tokens
*
* @param FieldInterface $field
* @param RuleInterface $rule
*
* @return string
*/
protected function buildMessage(FieldInterface $field, RuleInterface $rule, $value)
{
// Build an array with all the token values
$tokens = array(
'name' => $field->getName(),
'label' => $field->getLabel(),
'value' => $value,
) + $rule->getMessageParameters();
return $this->processMessageTokens($tokens, $rule->getMessage());
}
/**
* Replaces any {} tokens with the matching value from $tokens.
*
* @param array $tokens Associative array of token names and values
* @param string $message
*
* @return string
*
* @since 2.0
*/
protected function processMessageTokens(array $tokens, $message)
{
foreach ($tokens as $token => $value)
{
// Only string values can be used in a message
if (is_scalar($value) or method_exists($value, '__toString'))
{
$message = str_replace('{' . $token . '}', $value, $message);
}
}
return $message;
}
/**
* @param string $fieldName
*
* @return RuleInterface[]
*/
public function getFieldRules($fieldName)
{
try
{
$field = $this->getField($fieldName);
}
catch (InvalidFieldException $ife)
{
// No field found so no rules
return array();
}
return $field->getRules();
}
/**
* Allows validation rules to be dynamically added using method chaining.
*
* @param string $name
* @param array $arguments
*
* @return $this
* @throws InvalidRuleException
*
* @since 2.0
*/
public function __call($name, $arguments)
{
// Create and then add the new rule to the last added field
$rule = $this->createRuleInstance($name, $arguments);
$this->addRule($this->lastAddedField, $rule);
return $this;
}
/**
* Sets the failure message for the last added rule
*
* @param string $message
*
* @return $this
*
* @throws LogicException
*
* @since 2.0
*/
public function setMessage($message)
{
if ( ! $this->lastAddedRule)
{
throw new LogicException('VAL-006: A rule should be added before setting a message.');
}
$this->lastAddedRule->setMessage($message);
return $this;
}
/**
* Creates an instance of the given rule name
*
* @param string $name
* @param mixed $parameters
*
* @return RuleInterface
*
* @throws InvalidRuleException
*
* @since 2.0
*/
public function createRuleInstance($name, $parameters = [])
{
$className = $this->getRuleClassName($name);
if ( ! class_exists($className))
{
throw new InvalidRuleException($name);
}
/* @var RuleInterface $instance */
$reflection = new \ReflectionClass($className);
$instance = $reflection->newInstanceArgs($parameters);
// Check if there is a custom message
$message = $this->getGlobalMessage($name);
if ($message !== null)
{
$instance->setMessage($message);
}
return $instance;
}
/**
* Returns the full class name for the given validation rule
*
* @param string $name
*
* @return string
*
* @since 2.0
*/
protected function getRuleClassName($name)
{
// Check if we have a custom rule registered
if (isset($this->customRules[$name]))
{
// We do so grab the class name from the store
return $this->customRules[$name];
}
return $this->ruleNamespace . ucfirst($name);
}
/**
* Adds custom validation rules and allows for core rules to be overridden.
* When wanting to override a core rule just specify the rule name as $name.
* Eg, 'required', 'minLength'. Note the lowercase first letter.
*
* The name of the rule should not contain any whitespace or special characters as the name will be available
* to use as a function name in the method chaining syntax.
*
* @param string $name
* @param string $class
*
* @return $this
*
* @since 2.0
*/
public function addCustomRule($name, $class)
{
$this->customRules[$name] = $class;
return $this;
}
/**
* Sets a custom message for all fields of the given type that are created after the message has been set.
*
* @param string $ruleName Name of the rule to set a message for, eg, required, number, exactLength
* @param string|null $message Set to null to disable the custom message
*
* @return $this
*
* @since 2.0
*/
public function setGlobalMessage($ruleName, $message)
{
$this->messages[$ruleName] = $message;
if ($message === null)
{
$this->removeGlobalMessage($ruleName);
}
return $this;
}
/**
* Sets custom messages for one or more rules. Setting the value to "null" will remove the message
*
* @param string[] $messages
*
* @return $this
*
* @since 2.0
*/
public function setGlobalMessages($messages)
{
foreach ($messages as $name => $value)
{
$this->setGlobalMessage($name, $value);
}
return $this;
}
/**
* Removes a global rule message
*
* @param string $ruleName
*
* @return $this
*
* @since 2.0
*/
public function removeGlobalMessage($ruleName)
{
unset($this->messages[$ruleName]);
return $this;
}
/**
* Gets the global message set for a rule
*
* @param string $ruleName
*
* @return null|string Will be null if there is no message
*/
public function getGlobalMessage($ruleName)
{
if ( ! isset($this->messages[$ruleName]))
{
return null;
}
return $this->messages[$ruleName];
}
}