forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidation.php
More file actions
576 lines (488 loc) · 14.3 KB
/
Copy pathValidation.php
File metadata and controls
576 lines (488 loc) · 14.3 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 namespace CodeIgniter\Validation;
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2017, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author CodeIgniter Dev Team
* @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 3.0.0
* @filesource
*/
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\View\RendererInterface;
class Validation implements ValidationInterface
{
/**
* Files to load with validation functions.
*
* @var array
*/
protected $ruleSetFiles;
/**
* The loaded instances of our validation files.
*
* @var array
*/
protected $ruleSetInstances = [];
/**
* Stores the actual rules that should
* be ran against $data.
*
* @var array
*/
protected $rules = [];
/**
* The data that should be validated,
* where 'key' is the alias, with value.
*
* @var array
*/
protected $data = [];
/**
* Any generated errors during validation.
* 'key' is the alias, 'value' is the message.
*
* @var array
*/
protected $errors = [];
/**
* Stores custom error message to use
* during validation. Where 'key' is the alias.
*
* @var array
*/
protected $customErrors = [];
/**
* @var \Config\Validation
*/
protected $config;
protected $view;
//--------------------------------------------------------------------
/**
* Validation constructor.
*
* @param \Config\Validation $config
* @param RenderableInterface $view
*/
public function __construct($config, RendererInterface $view)
{
$this->ruleSetFiles = $config->ruleSets;
$this->config = $config;
$this->view = $view;
}
//--------------------------------------------------------------------
/**
* Runs the validation process, returning true/false determining whether
* or not validation was successful.
*
* @param array $data The array of data to validate.
* @param string $group The pre-defined group of rules to apply.
*
* @return bool
*/
public function run(array $data = null, string $group = null): bool
{
$data = $data ?? $this->data;
$this->loadRuleSets();
$this->loadRuleGroup($group);
// Run through each rule. If we have any field set for
// this rule, then we need to run them through!
foreach ($this->rules as $rField => $ruleString)
{
// Blast $ruleString apart, unless it's already an array.
$rules = $ruleString;
if (is_string($rules))
{
$rules = explode('|', $rules);
}
$this->processRules($rField, $data[$rField] ?? null, $rules, $data);
}
return count($this->errors) > 0
? false
: true;
}
//--------------------------------------------------------------------
/**
* Runs all of $rules against $field, until one fails, or
* all of them have been processed. If one fails, it adds
* the error to $this->errors and moves on to the next,
* so that we can collect all of the first errors.
*
* @param $value
* @param array|null $rules
* @param array $data // All of the fields to check.
*
* @return bool
*/
protected function processRules(string $field, $value, $rules = null, array $data)
{
foreach ($rules as $rule)
{
$callable = is_callable($rule);
$passed = false;
// Rules can contain parameters: max_length[5]
$param = false;
if (! $callable && preg_match('/(.*?)\[(.*)\]/', $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
// Placeholder for custom errors from the rules.
$error = null;
// If it's a callable, call and and get out of here.
if ($callable)
{
$passed = $param === false
? $rule($value)
: $rule($value, $param, $data);
}
else
{
$found = false;
// Check in our rulesets
foreach ($this->ruleSetInstances as $set)
{
if (! method_exists($set, $rule))
{
continue;
}
$found = true;
$passed = $param === false
? $set->$rule($value, $error)
: $set->$rule($value, $param, $data, $error);
break;
}
// If the rule wasn't found anywhere, we
// should throw an exception so the developer can find it.
if (! $found)
{
throw new \InvalidArgumentException(lang('Validation.ruleNotFound'));
}
}
// Set the error message if we didn't survive.
if ($passed === false)
{
$this->errors[$field] = is_null($error)
? $this->getErrorMessage($rule, $field)
: $error;
return false;
}
}
return true;
}
//--------------------------------------------------------------------
/**
* Takes a Request object and grabs the data to use from its
* POST array values.
*
* @param \CodeIgniter\HTTP\RequestInterface $request
*
* @return \CodeIgniter\Validation\Validation
*/
public function withRequest(RequestInterface $request): ValidationInterface
{
$this->data = $request->getPost() ?? [];
return $this;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Rules
//--------------------------------------------------------------------
/**
* Sets an individual rule and custom error messages for a single field.
*
* The custom error message should be just the messages that apply to
* this field, like so:
*
* [
* 'rule' => 'message',
* 'rule' => 'message'
* ]
*
* @param string $field
* @param string $rule
* @param array $errors
*
* @return $this
*/
public function setRule(string $field, string $rule, array $errors = [])
{
$this->rules[$field] = $rule;
$this->customErrors = array_merge($this->customErrors, $errors);
return $this;
}
//--------------------------------------------------------------------
/**
* Stores the rules that should be used to validate the items.
* Rules should be an array formatted like:
*
* [
* 'field' => 'rule1|rule2'
* ]
*
* The $errors array should be formatted like:
* [
* 'field' => [
* 'rule' => 'message',
* 'rule' => 'message
* ],
* ]
*
* @param array $rules
* @param array $errors // An array of custom error messages
*
* @return \CodeIgniter\Validation\Validation
*/
public function setRules(array $rules, array $errors = []): ValidationInterface
{
$this->rules = $rules;
if (! empty($errors))
{
$this->customErrors = $errors;
}
return $this;
}
//--------------------------------------------------------------------
/**
* Returns all of the rules currently defined.
*
* @return array
*/
public function getRules()
{
return $this->rules;
}
//--------------------------------------------------------------------
/**
* Checks to see if the rule for key $field has been set or not.
*
* @param string $field
*
* @return bool
*/
public function hasRule(string $field): bool
{
return array_key_exists($field, $this->rules);
}
//--------------------------------------------------------------------
/**
* Returns the rendered HTML of the errors as defined in $template.
*
* @param string $template
*
* @return string
*/
public function listErrors(string $template = 'list'): string
{
if (! array_key_exists($template, $this->config->templates))
{
throw new \InvalidArgumentException($template.' is not a valid Validation template.');
}
return $this->view->setVar('errors', $this->getErrors())
->render($this->config->templates[$template]);
}
//--------------------------------------------------------------------
/**
* Displays a single error in formatted HTML as defined in the $template view.
*
* @param string $field
* @param string $template
*
* @return string
*/
public function showError(string $field, string $template = 'single'): string
{
if (! array_key_exists($field, $this->errors))
{
return '';
}
if (! array_key_exists($template, $this->config->templates))
{
throw new \InvalidArgumentException($template.' is not a valid Validation template.');
}
return $this->view->setVar('error', $this->getError($field))
->render($this->config->templates[$template]);
}
//--------------------------------------------------------------------
/**
* Loads all of the rulesets classes that have been defined in the
* Config\Validation and stores them locally so we can use them.
*/
protected function loadRuleSets()
{
if (empty($this->ruleSetFiles))
{
throw new \RuntimeException(lang('Validation.noRuleSets'));
}
foreach ($this->ruleSetFiles as $file)
{
$this->ruleSetInstances[] = new $file();
}
}
//--------------------------------------------------------------------
/**
* Loads custom rule groups (if set) into the current rules.
*
* Rules can be pre-defined in Config\Validation and can
* be any name, but must all still be an array of the
* same format used with setRules(). Additionally, check
* for {group}_errors for an array of custom error messages.
*
* @param string|null $group
*/
protected function loadRuleGroup(string $group = null)
{
if (empty($group))
{
return;
}
if (! isset($this->config->$group))
{
throw new \InvalidArgumentException(sprintf(lang('Validation.groupNotFound'), $group));
}
if (! is_array($this->config->$group))
{
throw new \InvalidArgumentException(sprintf(lang('Validation.groupNotArray'), $group));
}
$this->rules = $this->config->$group;
// If {group}_errors exists in the config file,
// then override our custom errors with them.
$errorName = $group.'_errors';
if (isset($this->config->$errorName))
{
$this->customErrors = $this->config->$errorName;
}
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Errors
//--------------------------------------------------------------------
/**
* Checks to see if an error exists for the given field.
*
* @param string $field
*
* @return bool
*/
public function hasError(string $field): bool
{
return array_key_exists($field, $this->errors);
}
//--------------------------------------------------------------------
/**
* Returns the error(s) for a specified $field (or empty string if not set).
*
* @param string $field
*
* @return string
*/
public function getError(string $field): string
{
return array_key_exists($field, $this->errors)
? $this->errors[$field]
: '';
}
//--------------------------------------------------------------------
/**
* Returns the array of errors that were encountered during
* a run() call. The array should be in the followig format:
*
* [
* 'field1' => 'error message',
* 'field2' => 'error message',
* ]
*
* @return array
*/
public function getErrors(): array
{
return $this->errors ?? [];
}
//--------------------------------------------------------------------
/**
* Sets the error for a specific field. Used by custom validation methods.
*
* @param string $field
* @param string $error
*
* @return \CodeIgniter\Validation\Validation
*/
public function setError(string $field, string $error): ValidationInterface
{
$this->errors[$field] = $error;
return $this;
}
//--------------------------------------------------------------------
/**
* Attempts to find the appropriate error message
*
* @param string $rule
* @param string $field
* @param string $param
*
* @return string
*/
protected function getErrorMessage(string $rule, string $field, string $param = null): string
{
// Check if custom message has been defined by user
if (isset($this->customErrors[$field][$rule]))
{
$message = $this->customErrors[$field][$rule];
}
else
{
// Try to grab a localized version of the message...
// lang() will return the rule name back if not found,
// so there will always be a string being returned.
$message = lang('Validation.'.$rule);
}
$message = str_replace('{field}', $field, $message);
$message = str_replace('{param}', $param, $message);
return $message;
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Misc
//--------------------------------------------------------------------
/**
* Resets the class to a blank slate. Should be called whenever
* you need to process more than one array.
*
* @return mixed
*/
public function reset(): ValidationInterface
{
$this->data = [];
$this->rules = [];
$this->errors = [];
$this->customErrors = [];
return $this;
}
//--------------------------------------------------------------------
}