/
Validation.zep
641 lines (529 loc) · 16 KB
/
Validation.zep
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <team@phalcon.io>
*
* For the full copyright and license information, please view the
* LICENSE.txt file that was distributed with this source code.
*/
namespace Phalcon\Filter;
use Phalcon\Di\Di;
use Phalcon\Di\DiInterface;
use Phalcon\Di\Injectable;
use Phalcon\Filter\FilterInterface;
use Phalcon\Messages\MessageInterface;
use Phalcon\Messages\Messages;
use Phalcon\Filter\Validation\ValidationInterface;
use Phalcon\Filter\Validation\Exception;
use Phalcon\Filter\Validation\ValidatorInterface;
use Phalcon\Filter\Validation\AbstractCombinedFieldsValidator;
/**
* Allows to validate data using custom or built-in validators
*/
class Validation extends Injectable implements ValidationInterface
{
/**
* @var array
*/
protected combinedFieldsValidators = [];
/**
* @var mixed
*/
protected data;
/**
* @var object|null
*/
protected entity = null;
/**
* @var array
*/
protected filters = [];
/**
* @var array
*/
protected labels = [];
/**
* @var Messages|null
*/
protected messages = null;
/**
* List of validators
*
* @var array
*/
protected validators = [];
/**
* Calculated values
*
* @var array
*/
protected values = [];
/**
* Phalcon\Filter\Validation constructor
*/
public function __construct(array validators = [])
{
let this->validators = array_filter(
validators,
function(var element) {
return typeof element[0] != "array" || !(element[1] instanceof AbstractCombinedFieldsValidator);
}
);
let this->combinedFieldsValidators = array_filter(
validators,
function(var element) {
return typeof element[0] == "array" && element[1] instanceof AbstractCombinedFieldsValidator;
}
);
/**
* Check for an 'initialize' method
*/
if method_exists(this, "initialize") {
this->{"initialize"}();
}
}
/**
* Adds a validator to a field
*
* @param string|array $field
* @param ValidatorInterface $validator
*
* @return ValidationInterface
*/
public function add(var field, <ValidatorInterface> validator) -> <ValidationInterface>
{
var singleField;
if typeof field === "array" {
// Uniqueness validator for combination of fields is handled differently
if validator instanceof AbstractCombinedFieldsValidator {
let this->combinedFieldsValidators[] = [field, validator];
} else {
for singleField in field {
let this->validators[singleField][] = validator;
}
}
} elseif typeof field == "string" {
let this->validators[field][] = validator;
} else {
throw new Exception(
"Field must be passed as array of fields or string"
);
}
return this;
}
/**
* Appends a message to the messages list
*
* @param MessageInterface $message
*/
public function appendMessage(<MessageInterface> message) -> <ValidationInterface>
{
var messages;
let messages = this->messages;
if typeof messages != "object" {
let messages = new Messages();
}
messages->appendMessage(message);
let this->messages = messages;
return this;
}
/**
* Assigns the data to an entity
* The entity is used to obtain the validation values
*
* @param object entity
* @param array|object data
*/
public function bind(entity, data) -> <ValidationInterface>
{
this->setEntity(entity);
if unlikely (typeof data != "array" && typeof data != "object") {
throw new Exception("Data to validate must be an array or object");
}
let this->data = data;
return this;
}
/**
* @return mixed
*/
public function getData() -> var
{
return this->data;
}
/**
* Returns the bound entity
*
* @return object
*/
public function getEntity() -> var
{
return this->entity;
}
/**
* Returns all the filters or a specific one
*/
public function getFilters(string field = null) -> var | null
{
var filters, fieldFilters;
let filters = this->filters;
if !field {
return filters;
}
if !fetch fieldFilters, filters[field] {
return null;
}
return fieldFilters;
}
/**
* Get label for field
*
* @param string field
*/
public function getLabel(var field) -> string
{
var labels, value;
let labels = this->labels;
if typeof field == "array" {
return join(", ", field);
}
if fetch value, labels[field] {
return value;
}
return field;
}
/**
* Returns the registered validators
*/
public function getMessages() -> <Messages>
{
return this->messages;
}
/**
* Returns the validators added to the validation
*/
public function getValidators() -> array
{
return this->validators;
}
/**
* Gets the a value to validate in the object entity source
*
* @param mixed $entity
* @param string $field
*/
public function getValueByEntity(var entity, string field) -> var | null
{
string method;
let method = "get" . camelize(field);
if method_exists(entity, method) {
return entity->{method}();
}
if method_exists(entity, "readAttribute") {
return entity->readAttribute(field);
}
if isset entity->{field} {
return entity->{field};
}
return null;
}
/**
* Gets the a value to validate in the array/object data source
*
* @param mixed $data
* @param string $field
*/
public function getValueByData(var data, string field) -> var | null
{
var value, values;
// Check if there is a calculated value
let values = this->values;
if fetch value, values[field] {
return value;
}
if typeof data === "array" {
if isset data[field] {
return data[field];
}
}
if typeof data === "object" {
if isset data->{field} {
return data->{field};
}
}
return null;
}
/**
* Gets the a value to validate in the array/object data source
*
* @param string $field
*/
public function getValue(string field) -> var | null
{
var entity, method, value, data, filters, fieldFilters,
container, filterService;
bool isRawFetched;
let isRawFetched = false;
let entity = this->entity;
let data = this->data;
// If the entity is an object use it to retrieve the values
if typeof entity == "object" {
let value = this->getValueByEntity(entity, field);
if value === null {
let isRawFetched = true;
let value = this->getValueByData(data, field);
}
} else {
if unlikely (typeof data != "array" && typeof data != "object") {
throw new Exception("There is no data to validate");
}
let value = this->getValueByData(data, field);
}
if value === null {
return null;
}
let filters = this->filters;
if fetch fieldFilters, filters[field] {
if fieldFilters {
let container = this->getDI();
if container === null {
let container = Di::getDefault();
if container === null {
throw new Exception(
"A dependency injection container is required to access the 'filter' service"
);
}
}
let filterService = <FilterInterface> container->getShared("filter");
if unlikely typeof filterService != "object" {
throw new Exception("Returned 'filter' service is invalid");
}
let value = filterService->sanitize(value, fieldFilters);
/**
* Set filtered value in entity
*/
if typeof entity == "object" && isRawFetched === false {
let method = "set" . camelize(field);
if method_exists(entity, method) {
entity->{method}(value);
} elseif method_exists(entity, "writeAttribute") {
entity->writeAttribute(field, value);
} elseif property_exists(entity, field) {
let entity->{field} = value;
}
}
return value;
}
}
// Cache the calculated value only if it's not entity
if typeof entity != "object" {
let this->values[field] = value;
}
return value;
}
/**
* Alias of `add` method
*
* @param string|array $field
* @param ValidatorInterface $validator
*
* @return ValidationInterface
*/
public function rule(var field, <ValidatorInterface> validator) -> <ValidationInterface>
{
return this->add(field, validator);
}
/**
* Adds the validators to a field
*/
public function rules(var field, array! validators) -> <ValidationInterface>
{
var validator;
for validator in validators {
if validator instanceof ValidatorInterface {
this->add(field, validator);
}
}
return this;
}
/**
* Sets the bound entity
*
* @param object entity
*/
public function setEntity(entity) -> void
{
if unlikely typeof entity != "object" {
throw new Exception("Entity must be an object");
}
let this->entity = entity;
}
/**
* Adds filters to the field
*
* @param string field
* @param array|string filters
*/
public function setFilters(var field, filters) -> <ValidationInterface>
{
var singleField;
if typeof field == "array" {
for singleField in field {
let this->filters[singleField] = filters;
}
} elseif typeof field == "string" {
let this->filters[field] = filters;
} else {
throw new Exception(
"Field must be passed as array of fields or string."
);
}
return this;
}
/**
* Adds labels for fields
*/
public function setLabels(array! labels) -> void
{
let this->labels = labels;
}
public function setValidators(array validators) -> <Validation>
{
let this->validators = validators;
return this;
}
/**
* Validate a set of data according to a set of rules
*
* @param array|object data
* @param object entity
*/
public function validate(var data = null, var entity = null) -> <Messages>
{
var combinedFieldsValidators, field, messages, scope, status, validator,
validatorData, validators;
let validatorData = this->validators,
combinedFieldsValidators = this->combinedFieldsValidators;
if unlikely typeof validatorData != "array" {
throw new Exception("There are no validators to validate");
}
/**
* Clear pre-calculated values
*/
let this->values = [];
/**
* Implicitly creates a Phalcon\Messages\Messages object
*/
let messages = new Messages();
if entity !== null {
this->setEntity(entity);
}
/**
* Validation classes can implement the 'beforeValidation' callback
*/
if method_exists(this, "beforeValidation") {
let status = this->{"beforeValidation"}(data, entity, messages);
if status === false {
return status;
}
}
let this->messages = messages;
if data !== null {
if unlikely (typeof data != "array" && typeof data != "object") {
throw new Exception("Invalid data to validate");
}
let this->data = data;
}
for field, validators in validatorData {
for validator in validators {
if unlikely typeof validator != "object" {
throw new Exception("One of the validators is not valid");
}
/**
* Call internal validations, if it returns true, then skip the
* current validator
*/
if this->preChecking(field, validator) {
continue;
}
/**
* Check if the validation must be canceled if this validator fails
*/
if validator->validate(this, field) === false {
if validator->getOption("cancelOnFail") {
break;
}
}
}
}
for scope in combinedFieldsValidators {
if unlikely typeof scope != "array" {
throw new Exception("The validator scope is not valid");
}
let field = scope[0],
validator = scope[1];
if unlikely typeof validator != "object" {
throw new Exception("One of the validators is not valid");
}
/**
* Call internal validations, if it returns true, then skip the
* current validator
*/
if this->preChecking(field, validator) {
continue;
}
/**
* Check if the validation must be canceled if this validator fails
*/
if validator->validate(this, field) === false {
if validator->getOption("cancelOnFail") {
break;
}
}
}
/**
* Get the messages generated by the validators
*/
if method_exists(this, "afterValidation") {
this->{"afterValidation"}(data, entity, this->messages);
}
return this->messages;
}
/**
* Internal validations, if it returns true, then skip the current validator
*
* @param array|string $field
* @param ValidatorInterface $validator
*/
protected function preChecking(var field, <ValidatorInterface> validator) -> bool
{
var singleField, allowEmpty, emptyValue, value;
array results = [];
if typeof field == "array" {
for singleField in field {
let results[] = this->preChecking(singleField, validator);
if in_array(false, results) {
return false;
}
return true;
}
} else {
let allowEmpty = validator->getOption("allowEmpty", false);
if allowEmpty {
if method_exists(validator, "isAllowEmpty") {
return validator->isAllowEmpty(this, field);
}
let value = this->getValue(field);
if typeof allowEmpty == "array" {
for emptyValue in allowEmpty {
if emptyValue === value {
return true;
}
}
return false;
}
return empty value;
}
}
return false;
}
}