forked from phalcon/cphalcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidation.zep
537 lines (442 loc) · 14.3 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
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <[email protected]>
*
* 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\DiInterface;
use Phalcon\Di\Injectable;
use Phalcon\Filter\FilterInterface;
use Phalcon\Messages\MessageInterface;
use Phalcon\Messages\Messages;
use Phalcon\Validation\ValidationInterface;
use Phalcon\Validation\Exception;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\AbstractCombinedFieldsValidator;
/**
* Allows to validate data using custom or built-in validators
*/
class Validation extends Injectable implements ValidationInterface
{
protected combinedFieldsValidators;
protected data { get };
protected entity;
protected filters = [];
protected labels = [];
protected messages;
protected validators { set };
protected values;
/**
* Phalcon\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
*/
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
*/
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;
}
/**
* 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 array/object data source
*/
public function getValue(string field) -> var | null
{
var entity, method, value, data, values, filters, fieldFilters,
container, 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}();
} elseif method_exists(entity, "readAttribute") {
let value = entity->readAttribute(field);
} elseif isset entity->{field} {
let value = entity->{field};
} else {
let value = null;
}
} else {
let data = this->data;
if unlikely (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];
}
} elseif typeof data == "object" {
if isset data->{field} {
let value = data->{field};
}
}
}
if value === null {
return null;
}
let filters = this->filters;
if fetch fieldFilters, filters[field] {
if fieldFilters {
let container = this->getDI();
if typeof container != "object" {
let container = Di::getDefault();
if unlikely typeof container != "object" {
throw new Exception(
Exception::containerServiceNotFound(
"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" {
let method = "set" . camelizedField;
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
*/
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;
}
/**
* 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 = 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 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
*/
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;
}
}