forked from zendframework/zendframework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Form.php
3400 lines (3059 loc) · 91.5 KB
/
Form.php
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Form
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Form;
use Countable,
Iterator,
Traversable,
Zend\Config\Config,
Zend\Registry,
Zend\Loader\PrefixPathLoader,
Zend\Loader\PrefixPathMapper,
Zend\Loader,
Zend\Json\Json,
Zend\View\Renderer\PhpRenderer,
Zend\View\Renderer as View,
Zend\Stdlib\ArrayUtils,
Zend\Translator,
Zend\Validator\Validator;
/**
* Zend_Form
*
* A rewrite on this component is planned. At the bare minimum, this class
* will be refactored to utilize the new PluginBroker implementation with
* regards to loading elements and decorators (though decorators may be
* either removed or pushed to a DecoratorChain). Potentially, it may be
* modified to accept a Zend\Filter\InputFilter instance, from which it would
* inject values and error messages into attached elements.
*
* @todo Convert to PluginBroker usage
* @category Zend
* @package Zend_Form
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Form implements Iterator, Countable, Validator
{
/**#@+
* Plugin loader type constants
*/
const DECORATOR = 'DECORATOR';
const ELEMENT = 'ELEMENT';
/**#@-*/
/**#@+
* Method type constants
*/
const METHOD_DELETE = 'delete';
const METHOD_GET = 'get';
const METHOD_POST = 'post';
const METHOD_PUT = 'put';
/**#@-*/
/**#@+
* Encoding type constants
*/
const ENCTYPE_URLENCODED = 'application/x-www-form-urlencoded';
const ENCTYPE_MULTIPART = 'multipart/form-data';
/**#@-*/
/**
* Form metadata and attributes
* @var array
*/
protected $_attribs = array();
/**
* Decorators for rendering
* @var array
*/
protected $_decorators = array();
/**
* Default display group class
* @var string
*/
protected $_defaultDisplayGroupClass = 'Zend\Form\DisplayGroup';
/**
* Form description
* @var string
*/
protected $_description;
/**
* Should we disable loading the default decorators?
* @var bool
*/
protected $_disableLoadDefaultDecorators = false;
/**
* Display group prefix paths
* @var array
*/
protected $_displayGroupPrefixPaths = array();
/**
* Groups of elements grouped for display purposes
* @var array
*/
protected $_displayGroups = array();
/**
* Global decorators to apply to all elements
* @var null|array
*/
protected $_elementDecorators;
/**
* Prefix paths to use when creating elements
* @var array
*/
protected $_elementPrefixPaths = array();
/**
* Form elements
* @var array
*/
protected $_elements = array();
/**
* Array to which elements belong (if any)
* @var string
*/
protected $_elementsBelongTo;
/**
* Custom form-level error messages
* @var array
*/
protected $_errorMessages = array();
/**
* Are there errors in the form?
* @var bool
*/
protected $_errorsExist = false;
/**
* Has the form been manually flagged as an error?
* @var bool
*/
protected $_errorsForced = false;
/**
* Form order
* @var int|null
*/
protected $_formOrder;
/**
* Whether or not form elements are members of an array
* @var bool
*/
protected $_isArray = false;
/**
* Form legend
* @var string
*/
protected $_legend;
/**
* Plugin loaders
* @var array
*/
protected $_loaders = array();
/**
* Allowed form methods
* @var array
*/
protected $_methods = array('delete', 'get', 'post', 'put');
/**
* Order in which to display and iterate elements
* @var array
*/
protected $_order = array();
/**
* Whether internal order has been updated or not
* @var bool
*/
protected $_orderUpdated = false;
/**
* Sub form prefix paths
* @var array
*/
protected $_subFormPrefixPaths = array();
/**
* Sub forms
* @var array
*/
protected $_subForms = array();
/**
* @var Translator
*/
protected $_translator;
/**
* Global default translation adapter
* @var Translator
*/
protected static $_translatorDefault;
/**
* is the translator disabled?
* @var bool
*/
protected $_translatorDisabled = false;
/**
* @var View
*/
protected $_view;
/**
* @var bool
*/
protected $_isRendered = false;
/**
* Constructor
*
* Registers form view helper as decorator
*
* @param mixed $options
* @return void
*/
public function __construct($options = null)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (is_array($options)) {
$this->setOptions($options);
}
// Extensions...
$this->init();
$this->loadDefaultDecorators();
}
/**
* Clone form object and all children
*
* @return void
*/
public function __clone()
{
$elements = array();
foreach ($this->getElements() as $name => $element) {
$elements[] = clone $element;
}
$this->setElements($elements);
$subForms = array();
foreach ($this->getSubForms() as $name => $subForm) {
$subForms[$name] = clone $subForm;
}
$this->setSubForms($subForms);
$displayGroups = array();
foreach ($this->_displayGroups as $group) {
$clone = clone $group;
$elements = array();
foreach ($clone->getElements() as $name => $e) {
$elements[] = $this->getElement($name);
}
$clone->setElements($elements);
$displayGroups[] = $clone;
}
$this->setDisplayGroups($displayGroups);
}
/**
* Reset values of form
*
* @return Form
*/
public function reset()
{
foreach ($this->getElements() as $element) {
$element->setValue(null);
}
foreach ($this->getSubForms() as $subForm) {
$subForm->reset();
}
return $this;
}
/**
* Initialize form (used by extending classes)
*
* @return void
*/
public function init()
{
}
/**
* Set form state from options array
*
* @param array $options
* @return Form
*/
public function setOptions(array $options)
{
if (isset($options['prefixPath'])) {
$this->addPrefixPaths($options['prefixPath']);
unset($options['prefixPath']);
}
if (isset($options['elementPrefixPath'])) {
$this->addElementPrefixPaths($options['elementPrefixPath']);
unset($options['elementPrefixPath']);
}
if (isset($options['displayGroupPrefixPath'])) {
$this->addDisplayGroupPrefixPaths($options['displayGroupPrefixPath']);
unset($options['displayGroupPrefixPath']);
}
if (isset($options['elementDecorators'])) {
$this->_elementDecorators = $options['elementDecorators'];
unset($options['elementDecorators']);
}
if (isset($options['elements'])) {
$this->setElements($options['elements']);
unset($options['elements']);
}
if (isset($options['defaultDisplayGroupClass'])) {
$this->setDefaultDisplayGroupClass($options['defaultDisplayGroupClass']);
unset($options['defaultDisplayGroupClass']);
}
if (isset($options['displayGroupDecorators'])) {
$displayGroupDecorators = $options['displayGroupDecorators'];
unset($options['displayGroupDecorators']);
}
if (isset($options['elementsBelongTo'])) {
$elementsBelongTo = $options['elementsBelongTo'];
unset($options['elementsBelongTo']);
}
if (isset($options['attribs'])) {
$this->addAttribs($options['attribs']);
unset($options['attribs']);
}
$forbidden = array(
'Options', 'Config', 'PluginLoader', 'SubForms', 'View', 'Translator',
'Attrib', 'Default',
);
foreach ($options as $key => $value) {
$normalized = ucfirst($key);
if (in_array($normalized, $forbidden)) {
continue;
}
$method = 'set' . $normalized;
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->setAttrib($key, $value);
}
}
if (isset($displayGroupDecorators)) {
$this->setDisplayGroupDecorators($displayGroupDecorators);
}
if (isset($elementsBelongTo)) {
$this->setElementsBelongTo($elementsBelongTo);
}
return $this;
}
/**
* Set form state from config object
*
* @param Config $config
* @return Form
*/
public function setConfig(Config $config)
{
return $this->setOptions($config->toArray());
}
// Loaders
/**
* Set plugin loaders for use with decorators and elements
*
* @param PrefixPathMapper $loader
* @param string $type 'decorator' or 'element'
* @return Form
* @throws Exception\InvalidArgumentException on invalid type
*/
public function setPluginLoader(PrefixPathMapper $loader, $type = null)
{
$type = strtoupper($type);
switch ($type) {
case self::DECORATOR:
case self::ELEMENT:
$this->_loaders[$type] = $loader;
return $this;
default:
throw new Exception\InvalidArgumentException(sprintf('Invalid type "%s" provided to setPluginLoader()', $type));
}
}
/**
* Retrieve plugin loader for given type
*
* $type may be one of:
* - decorator
* - element
*
* If a plugin loader does not exist for the given type, defaults are
* created.
*
* @param string $type
* @return Zend\Loader\PrefixPathMapper
*/
public function getPluginLoader($type = null)
{
$type = strtoupper($type);
if (!isset($this->_loaders[$type])) {
switch ($type) {
case self::DECORATOR:
$prefixSegment = 'Form\Decorator';
$pathSegment = 'Form/Decorator';
break;
case self::ELEMENT:
$prefixSegment = 'Form\Element';
$pathSegment = 'Form/Element';
break;
default:
throw new Exception\InvalidArgumentException(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
}
$this->_loaders[$type] = new PrefixPathLoader(
array('Zend\\' . $prefixSegment . '\\' => 'Zend/' . $pathSegment . '/')
);
}
return $this->_loaders[$type];
}
/**
* Add prefix path for plugin loader
*
* If no $type specified, assumes it is a base path for both filters and
* validators, and sets each according to the following rules:
* - decorators: $prefix = $prefix . '_Decorator'
* - elements: $prefix = $prefix . '_Element'
*
* Otherwise, the path prefix is set on the appropriate plugin loader.
*
* If $type is 'decorator', sets the path in the decorator plugin loader
* for all elements. Additionally, if no $type is provided,
* the prefix and path is added to both decorator and element
* plugin loader with following settings:
* $prefix . '\Decorator', $path . '/Decorator/'
* $prefix . '\Element', $path . '/Element/'
*
* @param string $prefix
* @param string $path
* @param string $type
* @return Form
* @throws Exception\InvalidArgumentException for invalid type
*/
public function addPrefixPath($prefix, $path, $type = null)
{
$type = strtoupper($type);
switch ($type) {
case self::DECORATOR:
case self::ELEMENT:
$loader = $this->getPluginLoader($type);
$loader->addPrefixPath($prefix, $path);
return $this;
case null:
$prefix = rtrim($prefix, '\\');
$path = rtrim($path, DIRECTORY_SEPARATOR);
foreach (array(self::DECORATOR, self::ELEMENT) as $type) {
$cType = ucfirst(strtolower($type));
$pluginPath = $path . DIRECTORY_SEPARATOR . $cType . DIRECTORY_SEPARATOR;
$pluginPrefix = $prefix . '\\' . $cType;
$loader = $this->getPluginLoader($type);
$loader->addPrefixPath($pluginPrefix, $pluginPath);
}
return $this;
default:
throw new Exception\InvalidArgumentException(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
}
}
/**
* Add many prefix paths at once
*
* @param array $spec
* @return Form
*/
public function addPrefixPaths(array $spec)
{
if (isset($spec['prefix']) && isset($spec['path'])) {
return $this->addPrefixPath($spec['prefix'], $spec['path']);
}
foreach ($spec as $type => $paths) {
if (is_numeric($type) && is_array($paths)) {
$type = null;
if (isset($paths['prefix']) && isset($paths['path'])) {
if (isset($paths['type'])) {
$type = $paths['type'];
}
$this->addPrefixPath($paths['prefix'], $paths['path'], $type);
}
} elseif (!is_numeric($type)) {
if (!isset($paths['prefix']) || !isset($paths['path'])) {
continue;
}
$this->addPrefixPath($paths['prefix'], $paths['path'], $type);
}
}
return $this;
}
/**
* Add prefix path for all elements
*
* @param string $prefix
* @param string $path
* @param string $type
* @return Form
*/
public function addElementPrefixPath($prefix, $path, $type = null)
{
$this->_elementPrefixPaths[] = array(
'prefix' => $prefix,
'path' => $path,
'type' => $type,
);
foreach ($this->getElements() as $element) {
$element->addPrefixPath($prefix, $path, $type);
}
foreach ($this->getSubForms() as $subForm) {
$subForm->addElementPrefixPath($prefix, $path, $type);
}
return $this;
}
/**
* Add prefix paths for all elements
*
* @param array $spec
* @return Form
*/
public function addElementPrefixPaths(array $spec)
{
$this->_elementPrefixPaths = $this->_elementPrefixPaths + $spec;
foreach ($this->getElements() as $element) {
$element->addPrefixPaths($spec);
}
return $this;
}
/**
* Add prefix path for all display groups
*
* @param string $prefix
* @param string $path
* @return Form
*/
public function addDisplayGroupPrefixPath($prefix, $path)
{
$this->_displayGroupPrefixPaths[] = array(
'prefix' => $prefix,
'path' => $path,
);
foreach ($this->getDisplayGroups() as $group) {
$group->addPrefixPath($prefix, $path);
}
return $this;
}
/**
* Add multiple display group prefix paths at once
*
* @param array $spec
* @return Form
*/
public function addDisplayGroupPrefixPaths(array $spec)
{
foreach ($spec as $key => $value) {
if (is_string($value) && !is_numeric($key)) {
$this->addDisplayGroupPrefixPath($key, $value);
continue;
}
if (is_string($value) && is_numeric($key)) {
continue;
}
if (is_array($value)) {
$count = count($value);
if (array_keys($value) === range(0, $count - 1)) {
if ($count < 2) {
continue;
}
$prefix = array_shift($value);
$path = array_shift($value);
$this->addDisplayGroupPrefixPath($prefix, $path);
continue;
}
if (array_key_exists('prefix', $value) && array_key_exists('path', $value)) {
$this->addDisplayGroupPrefixPath($value['prefix'], $value['path']);
}
}
}
return $this;
}
// Form metadata:
/**
* Set form attribute
*
* @param string $key
* @param mixed $value
* @return Form
*/
public function setAttrib($key, $value)
{
$key = (string) $key;
$this->_attribs[$key] = $value;
return $this;
}
/**
* Add multiple form attributes at once
*
* @param array $attribs
* @return Form
*/
public function addAttribs(array $attribs)
{
foreach ($attribs as $key => $value) {
$this->setAttrib($key, $value);
}
return $this;
}
/**
* Set multiple form attributes at once
*
* Overwrites any previously set attributes.
*
* @param array $attribs
* @return Form
*/
public function setAttribs(array $attribs)
{
$this->clearAttribs();
return $this->addAttribs($attribs);
}
/**
* Retrieve a single form attribute
*
* @param string $key
* @return mixed
*/
public function getAttrib($key)
{
$key = (string) $key;
if (!isset($this->_attribs[$key])) {
return null;
}
return $this->_attribs[$key];
}
/**
* Retrieve all form attributes/metadata
*
* @return array
*/
public function getAttribs()
{
return $this->_attribs;
}
/**
* Remove attribute
*
* @param string $key
* @return bool
*/
public function removeAttrib($key)
{
if (isset($this->_attribs[$key])) {
unset($this->_attribs[$key]);
return true;
}
return false;
}
/**
* Clear all form attributes
*
* @return Form
*/
public function clearAttribs()
{
$this->_attribs = array();
return $this;
}
/**
* Set form action
*
* @param string $action
* @return Form
*/
public function setAction($action)
{
return $this->setAttrib('action', (string) $action);
}
/**
* Get form action
*
* Sets default to '' if not set.
*
* @return string
*/
public function getAction()
{
$action = $this->getAttrib('action');
if (null === $action) {
$action = '';
$this->setAction($action);
}
return $action;
}
/**
* Set form method
*
* Only values in {@link $_methods()} allowed
*
* @param string $method
* @return Form
* @throws Exception\InvalidArgumentException
*/
public function setMethod($method)
{
$method = strtolower($method);
if (!in_array($method, $this->_methods)) {
throw new Exception\InvalidArgumentException(sprintf('"%s" is an invalid form method', $method));
}
$this->setAttrib('method', $method);
return $this;
}
/**
* Retrieve form method
*
* @return string
*/
public function getMethod()
{
if (null === ($method = $this->getAttrib('method'))) {
$method = self::METHOD_POST;
$this->setAttrib('method', $method);
}
return strtolower($method);
}
/**
* Set encoding type
*
* @param string $value
* @return Form
*/
public function setEnctype($value)
{
$this->setAttrib('enctype', $value);
return $this;
}
/**
* Get encoding type
*
* @return string
*/
public function getEnctype()
{
if (null === ($enctype = $this->getAttrib('enctype'))) {
$enctype = self::ENCTYPE_URLENCODED;
$this->setAttrib('enctype', $enctype);
}
return $this->getAttrib('enctype');
}
/**
* Filter a name to only allow valid variable characters
*
* @param string $value
* @param bool $allowBrackets
* @return string
*/
public function filterName($value, $allowBrackets = false)
{
$charset = '^a-zA-Z0-9_\x7f-\xff';
if ($allowBrackets) {
$charset .= '\[\]';
}
return preg_replace('/[' . $charset . ']/', '', (string) $value);
}
/**
* Set form name
*
* @param string $name
* @return Form
*/
public function setName($name)
{
$name = $this->filterName($name);
if ('' === (string)$name) {
throw new Exception\InvalidArgumentException('Invalid name provided; must contain only valid variable characters and be non-empty');
}
return $this->setAttrib('name', $name);
}
/**
* Get name attribute
*
* @return null|string
*/
public function getName()
{
return $this->getAttrib('name');
}
/**
* Get fully qualified name
*
* Places name as subitem of array and/or appends brackets.
*
* @return string
*/
public function getFullyQualifiedName()
{
return $this->getName();
}
/**
* Get element id
*
* @return string
*/
public function getId()
{
if (null !== ($id = $this->getAttrib('id'))) {
return $id;
}
$id = $this->getFullyQualifiedName();
// Bail early if no array notation detected
if (!strstr($id, '[')) {
return $id;
}
// Strip array notation
if ('[]' == substr($id, -2)) {
$id = substr($id, 0, strlen($id) - 2);
}
$id = str_replace('][', '-', $id);
$id = str_replace(array(']', '['), '-', $id);
$id = trim($id, '-');
return $id;
}
/**
* Set form legend
*
* @param string $value
* @return Form
*/
public function setLegend($value)
{
$this->_legend = (string) $value;
return $this;
}
/**
* Get form legend
*
* @return string
*/
public function getLegend()
{
return $this->_legend;
}
/**
* Set form description
*
* @param string $value
* @return Form
*/
public function setDescription($value)
{
$this->_description = (string) $value;
return $this;
}
/**
* Retrieve form description
*
* @return string
*/
public function getDescription()
{
return $this->_description;
}
/**
* Set form order
*
* @param int $index
* @return Form
*/
public function setOrder($index)
{
$this->_formOrder = (int) $index;
return $this;
}
/**
* Get form order
*
* @return int|null
*/
public function getOrder()
{
return $this->_formOrder;
}
/**
* When calling renderFormElements or render this method
* is used to set $_isRendered member to prevent repeatedly
* merging belongsTo setting
*/
protected function _setIsRendered()
{