/
Form.zep
921 lines (771 loc) · 21.1 KB
/
Form.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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/**
* 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\Forms;
use Countable;
use Iterator;
use Phalcon\Di\Injectable;
use Phalcon\Di\DiInterface;
use Phalcon\Filter\FilterInterface;
use Phalcon\Forms\Element\ElementInterface;
use Phalcon\Html\Attributes;
use Phalcon\Html\Attributes\AttributesInterface;
use Phalcon\Html\TagFactory;
use Phalcon\Messages\Messages;
use Phalcon\Tag;
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\ValidationInterface;
/**
* This component allows to build forms using an object-oriented interface
*/
class Form extends Injectable implements Countable, Iterator, AttributesInterface
{
/**
* @var AttributesInterface|null
*/
protected attributes = null;
/**
* @var array
*/
protected data = [];
/**
* @var array
*/
protected filteredData = [];
/**
* @var array
*/
protected elements = [];
/**
* @var array
*/
protected elementsIndexed = [];
/**
* @var object|null
*/
protected entity = null;
/**
* @var Messages|array|null
*/
protected messages = null;
/**
* @var int
*/
protected position = 0;
/**
* @var array
*/
protected options = [];
/**
* @var TagFactory|null
*/
protected tagFactory = null;
/**
* @var ValidationInterface|null
*/
protected validation = null;
/**
* @var array
*/
protected whitelist = [];
/**
* Phalcon\Forms\Form constructor
*/
public function __construct(var entity = null, array userOptions = [])
{
if unlikely (entity !== null && typeof entity != "object") {
throw new Exception("The base entity is not valid");
}
let this->entity = entity;
/**
* Update the user options
*/
let this->options = userOptions;
/**
* Set form attributes
*/
let this->attributes = new Attributes();
/**
* Check for an 'initialize' method and call it
*/
if method_exists(this, "initialize") {
this->{"initialize"}(entity, userOptions);
}
}
/**
* Adds an element to the form
*/
public function add(<ElementInterface> element, string position = null, bool type = null) -> <Form>
{
var name, key, value;
array elements;
/**
* Gets the element's name
*/
let name = element->getName();
/**
* Link the element to the form
*/
element->setForm(this);
if method_exists(element, "setTagFactory") && this->tagFactory !== null {
element->{"setTagFactory"}(this->tagFactory);
}
if position == null || empty this->elements {
/**
* Append the element by its name
*/
let this->elements[name] = element;
} else {
let elements = [];
/**
* Walk elements and add the element to a particular position
*/
for key, value in this->elements {
if key == position {
if type {
/**
* Add the element before position
*/
let elements[name] = element,
elements[key] = value;
} else {
/**
* Add the element after position
*/
let elements[key] = value,
elements[name] = element;
}
} else {
/**
* Copy the element to new array
*/
let elements[key] = value;
}
}
let this->elements = elements;
}
return this;
}
/**
* Binds data to the entity
*
* @param object entity
* @param array whitelist
*/
public function bind(array! data, var entity = null, array whitelist = []) -> <Form>
{
var filter, key, value, element, filters, container, filteredValue;
array assignData, filteredData;
string method;
if unlikely empty this->elements {
throw new Exception("There are no elements in the form");
}
if empty whitelist {
let whitelist = this->whitelist;
}
let filter = null;
let assignData = [];
let filteredData = [];
for key, value in data {
/**
* Get the element
*/
if !fetch element, this->elements[key] {
continue;
}
/**
* Check if the item is in the whitelist
*/
if !empty whitelist && !in_array(key, whitelist) {
continue;
}
/**
* Check if the method has filters
*/
let filters = element->getFilters();
if filters {
if typeof filter != "object" {
let container = this->getDI(),
filter = <FilterInterface> container->getShared("filter");
}
/**
* Sanitize the filters
*/
let filteredValue = filter->sanitize(value, filters);
} else {
let filteredValue = value;
}
let assignData[key] = value;
let filteredData[key] = filteredValue;
if entity !== null {
/**
* Use the setter if any available
*/
let method = "set" . camelize(key);
if method_exists(entity, method) {
entity->{method}(filteredValue);
continue;
}
/**
* Use the public property if it doesn't have a setter
*/
let entity->{key} = filteredValue;
}
}
let this->data = assignData;
let this->filteredData = filteredData;
return this;
}
/**
* Clears every element in the form to its default value
*
* @param array|string|null fields
*/
public function clear(var fields = null) -> <Form>
{
var elements, element, data, field;
let data = this->data,
elements = this->elements;
/**
* If fields is string, clear just that field.
* If it's array, clear only fields in array.
* If null, clear all
*/
if fields === null {
let data = [];
for element in elements {
element->clear();
}
} else {
if typeof fields != "array" {
let fields = [fields];
}
for field in fields {
if isset data[field] {
unset data[field];
}
if fetch element, elements[field] {
element->clear();
}
}
}
let this->data = data;
return this;
}
/**
* Returns the number of elements in the form
*/
public function count() -> int
{
return count(this->elements);
}
/**
* Returns the current element in the iterator
*/
public function current() -> mixed
{
var element;
if !fetch element, this->elementsIndexed[this->position] {
return false;
}
return element;
}
/**
* Returns an element added to the form by its name
*/
public function get(string! name) -> <ElementInterface>
{
var element;
if unlikely !fetch element, this->elements[name] {
throw new Exception(
"Element with ID=" . name . " is not part of the form"
);
}
return element;
}
/**
* Returns the form's action
*/
public function getAction() -> string
{
return (string) this->getAttributes()->get("action");
}
/**
* Get Form attributes collection
*/
public function getAttributes() -> <Attributes>
{
if unlikely null === this->attributes {
let this->attributes = new Attributes();
}
return this->attributes;
}
/**
* Returns the form elements added to the form
*/
public function getElements() -> <ElementInterface[]>
{
return this->elements;
}
/**
* Returns the entity related to the model
*
* @return object
*/
public function getEntity()
{
return this->entity;
}
/**
* Gets a value from the internal filtered data or calls getValue(name)
*/
public function getFilteredValue(string! name) -> var | null
{
var filteredData, value;
let filteredData = this->filteredData;
if typeof filteredData == "array" {
/**
* Check if the data is in the data array
*/
if fetch value, filteredData[name] {
return value;
}
}
return this->getValue(name);
}
/**
* Returns a label for an element
*/
public function getLabel(string! name) -> string
{
var element, label;
if unlikely !fetch element, this->elements[name] {
throw new Exception(
"Element with ID=" . name . " is not part of the form"
);
}
let label = element->getLabel();
/**
* Use the element's name as label if the label is not available
*/
if !label {
return name;
}
return label;
}
/**
* Returns the messages generated in the validation.
*
* ```php
* if ($form->isValid($_POST) == false) {
* $messages = $form->getMessages();
*
* foreach ($messages as $message) {
* echo $message, "<br>";
* }
* }
* ```
*/
public function getMessages() -> <Messages> | array
{
var messages;
let messages = this->messages;
if !(typeof messages == "object" && messages instanceof Messages) {
return new Messages();
}
return messages;
}
/**
* Returns the messages generated for a specific element
*/
public function getMessagesFor(string! name) -> <Messages>
{
if !this->has(name) {
return new Messages();
}
return this->get(name)->getMessages();
}
/**
* Returns the tagFactory object
*/
public function getTagFactory() -> <TagFactory> | null
{
return this->tagFactory;
}
/**
* Returns the value of an option if present
*/
public function getUserOption(string option, var defaultValue = null) -> var
{
var value;
if !fetch value, this->options[option] {
return defaultValue;
}
return value;
}
/**
* Returns the options for the element
*/
public function getUserOptions() -> array
{
return this->options;
}
/**
* Gets a value from the internal related entity or from the default value
*/
public function getValue(string! name) -> var | null
{
var entity, value, data, internalEntity, element;
array forbidden;
string method;
let entity = this->entity;
let data = this->data;
/**
* Check if form has a getter
*/
if method_exists(this, "getCustomValue") {
return this->{"getCustomValue"}(name, entity, data);
}
if typeof entity == "object" {
/**
* Check if the entity has a getter
*/
let method = "get" . camelize(name);
if method_exists(entity, method) {
return entity->{method}();
}
/**
* Check if the entity has a public property
*/
if fetch value, entity->{name} {
return value;
}
}
if typeof data == "array" {
/**
* Check if the data is in the data array
*/
if fetch value, data[name] {
return value;
}
}
let forbidden = [
"attributes": true,
"validation": true,
"action": true,
"useroption": true,
"useroptions": true,
"entity": true,
"elements": true,
"messages": true,
"messagesfor": true,
"label": true,
"value": true,
"di": true,
"tagFactory": true,
"eventsmanager": true
];
/**
* Check if the method is internal
*/
let internalEntity = strtolower(name);
if isset forbidden[internalEntity] {
return null;
}
/**
* Check if form has a getter
*/
let method = "get" . camelize(name);
if method_exists(this, method) {
return this->{method}();
}
/**
* Check if element has default value
*/
if fetch element, this->elements[name] {
return element->getDefault();
}
return null;
}
/**
* return ValidationInterface|null
*/
public function getValidation() -> <ValidationInterface> | null
{
return this->validation;
}
/**
* return array
*/
public function getWhitelist() -> array
{
return this->whitelist;
}
/**
* Check if the form contains an element
*/
public function has(string! name) -> bool
{
/**
* Checks if the element is in the form
*/
return isset this->elements[name];
}
/**
* Check if messages were generated for a specific element
*/
public function hasMessagesFor(string! name) -> bool
{
return this->getMessagesFor(name)->count() > 0;
}
/**
* Validates the form
*
* @param array data
* @param object entity
* @param array whitelist
*/
public function isValid(var data = null, var entity = null, array whitelist = []) -> bool
{
var messages, element, validators, name, filters, validator, validation,
elementMessage;
bool validationStatus;
if empty this->elements {
return true;
}
if empty whitelist {
let whitelist = this->whitelist;
}
/**
* If the data is not an array use the one passed previously
*/
if typeof data != "array" {
let data = this->data;
}
/**
* If the user doesn't pass an entity we use the one in this_ptr->entity
*/
if typeof entity != "object" && typeof this->entity == "object" {
let entity = this->entity;
}
this->bind(data, entity, whitelist);
/**
* Check if there is a method 'beforeValidation'
*/
if method_exists(this, "beforeValidation") {
if this->{"beforeValidation"}(data, entity) === false {
return false;
}
}
let validationStatus = true;
let validation = this->getValidation();
if typeof validation != "object" || !(validation instanceof ValidationInterface) {
// Create an implicit validation
let validation = new Validation();
}
for element in this->elements {
let validators = element->getValidators();
if count(validators) == 0 {
continue;
}
/**
* Element's name
*/
let name = element->getName();
/**
* Append (not overriding) element validators to validation class
*/
for validator in validators {
validation->add(name, validator);
}
/**
* Get filters in the element
*/
let filters = element->getFilters();
/**
* Assign the filters to the validation
*/
if typeof filters == "array" {
validation->setFilters(name, filters);
}
}
/**
* Perform the validation
*/
let messages = validation->validate(data, entity);
if messages->count() {
// Add validation messages to relevant elements
for elementMessage in iterator(messages) {
this->get(elementMessage->getField())->appendMessage(elementMessage);
}
messages->rewind();
let validationStatus = false;
}
/**
* If the validation fails update the messages
*/
if !validationStatus {
let this->messages = messages;
}
/**
* Check if there is a method 'afterValidation'
*/
if method_exists(this, "afterValidation") {
this->{"afterValidation"}(messages);
}
/**
* Return the validation status
*/
return validationStatus;
}
/**
* Returns the current position/key in the iterator
*/
public function key() -> int
{
return this->position;
}
/**
* Generate the label of an element added to the form including HTML
*/
public function label(string! name, array attributes = null) -> string
{
var element;
if unlikely !fetch element, this->elements[name] {
throw new Exception(
"Element with ID=" . name . " is not part of the form"
);
}
return element->label(attributes);
}
/**
* Moves the internal iteration pointer to the next position
*/
public function next() -> void
{
let this->position++;
}
/**
* Renders a specific item in the form
*/
public function render(string! name, array attributes = []) -> string
{
var element;
if unlikely !fetch element, this->elements[name] {
throw new Exception(
"Element with ID=" . name . " is not part of the form"
);
}
return element->render(attributes);
}
/**
* Removes an element from the form
*/
public function remove(string! name) -> bool
{
/**
* Checks if the element is in the form
*/
if isset this->elements[name] {
unset this->elements[name];
return true;
}
/**
* Clean the iterator index
*/
let this->elementsIndexed = null;
return false;
}
/**
* Rewinds the internal iterator
*/
public function rewind() -> void
{
let this->position = 0;
let this->elementsIndexed = array_values(this->elements);
}
/**
* Sets the form's action
*
* @return Form
*/
public function setAction(string! action) -> <Form>
{
this->getAttributes()->set("action", action);
return this;
}
/**
* Set form attributes collection
*/
public function setAttributes(<Attributes> attributes) -> <AttributesInterface>
{
let this->attributes = attributes;
return this;
}
/**
* Sets the entity related to the model
*
* @param object entity
*/
public function setEntity(var entity) -> <Form>
{
let this->entity = entity;
return this;
}
/**
* Sets the tagFactory for the form
*/
public function setTagFactory(<TagFactory> tagFactory) -> <Form>
{
let this->tagFactory = tagFactory;
return this;
}
/**
* Sets the default validation
*
* @param ValidationInterface validation
*/
public function setValidation(<ValidationInterface> validation) -> <Form>
{
let this->validation = validation;
return this;
}
/**
* Sets the default whitelist
*
* @param array whitelist
*/
public function setWhitelist(array whitelist) -> <Form>
{
let this->whitelist = whitelist;
return this;
}
/**
* Sets an option for the form
*/
public function setUserOption(string option, var value) -> <Form>
{
let this->options[option] = value;
return this;
}
/**
* Sets options for the element
*/
public function setUserOptions(array! options) -> <Form>
{
let this->options = options;
return this;
}
/**
* Check if the current element in the iterator is valid
*/
public function valid() -> bool
{
return isset this->elementsIndexed[this->position];
}
}