forked from phalcon/cphalcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidation.zep
595 lines (503 loc) · 13.4 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
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <team@phalconphp.com>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
namespace Phalcon;
use Phalcon\Di\Injectable;
use Phalcon\Messages\MessageInterface;
use Phalcon\Messages\Messages;
use Phalcon\ValidationInterface;
use Phalcon\Validation\Exception;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\CombinedFieldsValidator;
/**
* Phalcon\Validation
*
* Allows to validate data using custom or built-in validators
*/
class Validation extends Injectable implements ValidationInterface
{
protected _data { get };
protected _entity;
protected _validators = [] { set };
protected _combinedFieldsValidators = [];
protected _filters = [];
protected _messages;
protected _defaultMessages;
protected _labels = [];
protected _values;
/**
* Phalcon\Validation constructor
*/
public function __construct(array validators = null)
{
if count(validators) {
let this->_validators = array_filter(validators, function(var element) {
return typeof element[0] != "array" || !(element[1] instanceof CombinedFieldsValidator);
});
let this->_combinedFieldsValidators = array_filter(validators, function(var element) {
return typeof element[0] == "array" && element[1] instanceof CombinedFieldsValidator;
});
}
this->setDefaultMessages();
/**
* Check for an 'initialize' method
*/
if method_exists(this, "initialize") {
this->{"initialize"}();
}
}
/**
* 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 validators, messages, scope, field, validator, status, combinedFieldsValidators;
let validators = this->_validators;
let combinedFieldsValidators = this->_combinedFieldsValidators;
if typeof validators != "array" {
throw new Exception("There are no validators to validate");
}
/**
* Clear pre-calculated values
*/
let this->_values = null;
/**
* 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 typeof data == "array" || typeof data == "object" {
let this->_data = data;
} else {
throw new Exception("Invalid data to validate");
}
}
for scope in validators {
if typeof scope != "array" {
throw new Exception("The validator scope is not valid");
}
let field = scope[0],
validator = scope[1];
if 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 typeof scope != "array" {
throw new Exception("The validator scope is not valid");
}
let field = scope[0],
validator = scope[1];
if 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;
}
/**
* Adds a validator to a field
*/
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 CombinedFieldsValidator {
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;
}
/**
* Alias of `add` method
*/
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;
}
/**
* 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;
}
/**
* Returns all the filters or a specific one
*
* @return mixed
*/
public function getFilters(string field = null)
{
var filters, fieldFilters;
let filters = this->_filters;
if field === null || field === "" {
return filters;
}
if !fetch fieldFilters, filters[field] {
return null;
}
return fieldFilters;
}
/**
* Returns the validators added to the validation
*/
public function getValidators() -> array
{
return this->_validators;
}
/**
* Sets the bound entity
*
* @param object entity
*/
public function setEntity(entity)
{
if typeof entity != "object" {
throw new Exception("Entity must be an object");
}
let this->_entity = entity;
}
/**
* Returns the bound entity
*
* @return object
*/
public function getEntity()
{
return this->_entity;
}
/**
* Adds default messages to validators
*/
public function setDefaultMessages(array messages = []) -> array
{
var defaultMessages;
let defaultMessages = [
"Alnum": "Field :field must contain only letters and numbers",
"Alpha": "Field :field must contain only letters",
"Between": "Field :field must be within the range of :min to :max",
"Confirmation": "Field :field must be the same as :with",
"Digit": "Field :field must be numeric",
"Email": "Field :field must be an email address",
"ExclusionIn": "Field :field must not be a part of list: :domain",
"FileEmpty": "Field :field must not be empty",
"FileIniSize": "File :field exceeds the maximum file size",
"FileMaxResolution": "File :field must not exceed :max resolution",
"FileMinResolution": "File :field must be at least :min resolution",
"FileSize": "File :field exceeds the size of :max",
"FileType": "File :field must be of type: :types",
"FileValid": "Field :field is not valid",
"Identical": "Field :field does not have the expected value",
"InclusionIn": "Field :field must be a part of list: :domain",
"Numericality": "Field :field does not have a valid numeric format",
"PresenceOf": "Field :field is required",
"Regex": "Field :field does not match the required format",
"TooLong": "Field :field must not exceed :max characters long",
"TooShort": "Field :field must be at least :min characters long",
"Uniqueness": "Field :field must be unique",
"Url": "Field :field must be a url",
"CreditCard": "Field :field is not valid for a credit card number",
"Date": "Field :field is not a valid date"
];
let this->_defaultMessages = array_merge(defaultMessages, messages);
return this->_defaultMessages;
}
/**
* Get default message for validator type
*/
public function getDefaultMessage(string! type) -> string
{
var defaultMessage;
if fetch defaultMessage, this->_defaultMessages[type] {
return defaultMessage;
}
return "";
}
/**
* Returns the registered validators
*/
public function getMessages() -> <Messages>
{
return this->_messages;
}
/**
* Adds labels for fields
*/
public function setLabels(array! labels)
{
let this->_labels = labels;
}
/**
* 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;
}
/**
* Appends a message to the messages list
*/
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>
{
if typeof entity != "object" {
throw new Exception("Entity must be an object");
}
if typeof data != "array" && typeof data != "object" {
throw new Exception("Data to validate must be an array or object");
}
let this->_entity = entity,
this->_data = data;
return this;
}
/**
* Gets the a value to validate in the array/object data source
*/
public function getValue(string field) -> var | null
{
var entity, method, value, data, values,
filters, fieldFilters, dependencyInjector,
filterService, camelizedField;
let entity = this->_entity;
// If the entity is an object use it to retrieve the values
if typeof entity == "object" {
let camelizedField = camelize(field);
let method = "get" . camelizedField;
if method_exists(entity, method) {
let value = entity->{method}();
} else {
if method_exists(entity, "readAttribute") {
let value = entity->readAttribute(field);
} else {
if isset entity->{field} {
let value = entity->{field};
} else {
let value = null;
}
}
}
}
else {
let data = this->_data;
if typeof data != "array" && typeof data != "object" {
throw new Exception("There is no data to validate");
}
// Check if there is a calculated value
let values = this->_values;
if fetch value, values[field] {
return value;
}
let value = null;
if typeof data == "array" {
if isset data[field] {
let value = data[field];
}
} else {
if typeof data == "object" {
if isset data->{field} {
let value = data->{field};
}
}
}
}
if typeof value == "null" {
return null;
}
let filters = this->_filters;
if fetch fieldFilters, filters[field] {
if fieldFilters {
let dependencyInjector = this->getDI();
if typeof dependencyInjector != "object" {
let dependencyInjector = Di::getDefault();
if typeof dependencyInjector != "object" {
throw new Exception("A dependency injector is required to obtain the 'filter' service");
}
}
let filterService = dependencyInjector->getShared("filter");
if 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" {
let method = "set" . camelizedField;
if method_exists(entity, method) {
entity->{method}(value);
} else {
if method_exists(entity, "writeAttribute") {
entity->writeAttribute(field, value);
} else {
if 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;
}
/**
* Internal validations, if it returns true, then skip the current validator
*/
protected function preChecking(var field, <ValidatorInterface> validator) -> bool
{
var singleField, allowEmpty, emptyValue, value, result;
if typeof field == "array" {
for singleField in field {
let result = this->preChecking(singleField, validator);
if result {
return result;
}
}
}
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;
}
}