-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm.php
399 lines (341 loc) · 10.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
<?php
namespace NitroXy\PHPForms;
class Form extends FormContext {
const LAYOUT_TWOROWS = 1;
const LAYOUT_FILL = 2;
static public $defaultBuilderClass = FormBuilder::class;
static public $defaultResourceClass = FormData::class;
static protected $base_options = array(
'method' => 'post', /* form method (get or post) */
'method_field_name' => '_method', /* name of the method field when method isn't GET or POST. */
'action' => '', /* form action (if set to false no <form> wrapper will be generated (you must manually set it) */
'layout' => 'table', /* layout engine, one of {plain, table, bootstrap, unbuffered} or a class extending FormLayout. If unbuffered fields is written directly. */
'prefix' => false, /* use a custom prefix in front of all names, default is nothing for arrays and class name for objects */
'class' => [], /* additional classes (accepts string or array) */
);
public $id = "";
public $attr = [];
protected $res = null;
private $name_pattern = '%s';
private $layout = null;
private $callback = null;
private $options = [];
private $unbuffered = false;
protected static $formFieldIdCounter = 1;
/**
* Override to set defaults for subclassed form.
* Should return an array with options. See $base_options.
*/
static protected function defaultOptions(){
return [];
}
/**
* Override to support CSRF tokens.
* It should return a string with the CSRF token or false to disable. Tokens
* is automatically appended to all forms but it will not validate it (user
* must check for presence and validate)
*/
static protected function csrfToken(){
return false;
}
/**
* Create a form bound to an key-value array.
*/
static public function fromArray($id, array $array=null, callable $callback, array $options=[]){
$form = static::createInstance($id, $callback);
$form->parseOptions($options);
$form->createResource($array);
$form->render();
}
/**
* Create a form bound to an object.
*
* Name will use class name as prefix, e.g name="Foo[field]".
*/
static public function fromObject($obj=null, callable $callback, array $options=[]){
$form = static::createInstance(get_class($obj), $callback);
$form->setNamePattern($obj);
$form->parseOptions($options);
$form->createResource($obj);
$form->addClass(get_class($obj));
$object_id = $form->res->getId();
if ( $object_id !== false ){
/* use a unique html id if the object has an id, makes it possible to use form for multiple objects of same type */
$form->setId($form->id . "_{$object_id}");
/* automatically add a hidden with the object id */
$form->hiddenField("id");
}
$form->render();
}
/**
* Create a resource-less form.
*/
static public function create($id, $callback, array $options=[]){
$form = static::createInstance($id, $callback);
$form->parseOptions($options);
$form->createResource(null);
$form->render();
}
public function __construct($id, callable $callback) {
$builderClass = static::$defaultBuilderClass;
$builder = new $builderClass;
$builder->setContext($this);
parent::__construct($this, $builder);
$this->setId($id);
$this->addClass('form');
$this->callback = $callback;
}
/**
* Creates an instance of the called form class.
* Just like "new Form()" but works with late static binding so an inherited
* class can call "MyForm::fromObject(..)" and still get a MyForm instance.
*/
protected static function createInstance($id, callable $callback){
$classname = get_called_class();
return new $classname($id, $callback);
}
protected function createResource($src){
$classname = static::$defaultResourceClass;
$this->res = new $classname($src);
}
protected function popAttr($key, &$attr, &$value){
if ( array_key_exists($key, $attr) ){
$value = $attr[$key];
unset($attr[$key]);
return true;
}
return false;
}
protected function parseOptions($user){
$options = array_merge(
static::$base_options,
static::defaultOptions(),
$user
);
/* extract non-attribute options */
$this->popAttr('method_field_name', $options, $this->options['method_field_name']);
/* layout */
$this->popAttr('layout', $options, $layout);
$this->setLayout($layout);
/* rewrite requested action to GET/POST and store original method */
$this->popAttr('method', $options, $method);
$this->options['requested_method'] = $method;
$this->attr['method'] = static::parseMethod($method);
/* custom prefix */
$this->popAttr('prefix', $options, $prefix);
if ( $prefix ){
$this->setNamePattern($prefix);
}
/* classes require deeper merge: classes has already been added */
$this->popAttr('class', $options, $class);
$this->addClass($class);
/* merge form attributes */
$attr = [];
$this->popAttr('attr', $options, $attr);
$this->attr = array_merge(
$this->attr,
$options,
$attr
);
}
protected function setNamePattern($prefix){
if ( is_object($prefix) ){
$this->name_pattern = get_class($prefix) . '[%s]';
} else if ( is_string($prefix) ){
if ( strstr($prefix, '%s') === false ){
$this->name_pattern = $prefix . '[%s]';
} else {
$this->name_pattern = $prefix;
}
} else {
$this->name_pattern = '%s';
}
}
protected function setId($id){
$this->attr['id'] = $this->id = $id;
}
protected function addClass($class){
if ( is_string($class) ){
$class = explode(' ', $class);
}
if ( !array_key_exists('class', $this->attr) ){
$this->attr['class'] = [];
}
$this->attr['class'] = array_merge($this->attr['class'], $class);
}
private function parseMethod($method){
$method = strtoupper($method);
switch ( $method ){
case 'GET':
case 'POST':
return $method;
default:
return 'POST';
}
}
private function setLayout($layout){
$class = $layout;
if ( is_string($layout) ){
switch ( $layout ){
case 'table': $layout = new FormLayoutTable(); break;
case 'plain': $layout = new FormLayoutPlain(); break;
case 'bootstrap': $layout = new FormLayoutBootstrap(); break;
case 'unbuffered':
$layout = new FormLayoutUnbuffered();
$this->unbuffered = true;
break;
default:
trigger_error("Form class called with unknown layout `$layout'", E_USER_NOTICE);
$layout = new FormLayoutPlain();
}
} else if ( !$layout instanceof FormLayoutInterface ){
trigger_error("Layout must either be string or a class implementing FormLayout", E_USER_ERROR);
} else {
if ( method_exists($layout, 'layoutName') ){
$class = $layout->layoutName();
} else {
$class = get_class($layout);
}
}
/* use layout class so it is possible to style a single layout */
$this->addClass($class);
$this->layout = $layout;
}
public function unbuffered(){
return $this->unbuffered ? $this->layout : false;
}
protected function render(){
$cb = $this->callback;
$this->start();
$this->apply($cb);
$this->end();
}
/**
* This creates a subform.
* Example:
* new Form("foo", function($f) {
* $f->fieldsFor($object_type_derp, function($fo) {
* $fo->textField('moo');
* });
* $f->fieldsFor($object_type_herp, function($fo) {
* $fo->textField('boo');
* });
* });
*
* This would generate the form with id "foo" and the fields
* Derp[moo] (textField)
* Herp[boo] (textField)
* (given that Derp and Herp are the class-name of the models given to fieldsFor
*/
public function fieldsFor($id, $obj, callable $callback) {
$old = [$this->res, $this->id, $this->name_pattern];
$this->id = $id;
$this->name_pattern = $id . '[%s]';
$this->createResource($obj);
if ( is_object($obj) ) {
$this->hiddenField("id");
}
$this->apply($callback);
list($this->res, $this->id, $this->name_pattern) = $old;
}
/**
* Overridden hidden so child-containers can call this.
*/
public function hiddenField($key, $value=null, array $attr=[]) {
if ( $value !== null ){
$attr['value'] = $value;
}
$this->hidden[] = $this->builder->factory("hidden", $key, false, $attr);
}
public function methodField() {
$this->hiddenField($this->options['method_field_name'], strtoupper($this->options['requested_method']));
}
protected function start() {
if ( $this->attr['action'] !== false ){
$this->layout->preamble($this);
}
}
protected function end() {
$method = strtoupper($this->options['requested_method']);
if ( $method !== "GET" ) {
$has_csrf = false;
foreach( $this->hidden as $field) {
if($field->getName() == "csrf_token") {
$has_csrf = true;
break;
}
}
if ( !$has_csrf && ($csrf_token=$this->csrfToken()) ) {
$this->hiddenField("csrf_token", $csrf_token);
}
/* use a special _method field to allow using other HTTP methods
* such as PATCH and DELETE. */
if ( $method !== 'POST' ){
$this->methodField();
}
}
if ( $this->unbuffered ){
if ( $this->attr['action'] !== false ){
echo "</form>\n";
}
return;
}
/* output all hidden fields */
foreach ( $this->hidden as $field ){
$field->render($this->layout, $this->res);
}
/* output regular fields */
foreach ( $this->fields as $field ){
$field->render($this->layout, $this->res);
}
$this->layout->end();
if ( $this->attr['action'] !== false ){
$this->layout->postamble($this);
}
}
private function getValue($key, array &$attr) {
if ( array_key_exists('value', $attr) ){
$value = $attr['value'];
unset($attr['value']);
return $value;
}
return $this->res->getValueFor($key);
}
public function generateId($key, array &$attr){
if ( array_key_exists('id', $attr) ){
$id = $attr['id'];
unset($attr['id']);
return $id;
}
/* no id unless key is present */
if ( empty($key) ){
return null;
}
/* when form doesn't have ID use an autogenerated prefix */
if ( empty($this->id) ){
$counter = static::$formFieldIdCounter++;
return "_Form_Field_{$counter}_$key";
}
return "{$this->id}_$key";
}
public function generateName($key, array &$attr){
if ( array_key_exists('name', $attr) ){
$name = $attr['name'];
unset($attr['name']);
return $name;
}
/* special cases for fields (like CSRF token) which should always
* be named as such (no prefix) */
if ( $key === 'csrf_token' || $key === $this->options['method_field_name'] ){
return $key;
}
if ( empty($key) ) return null;
return sprintf($this->name_pattern, $key);
}
public function generateData($key, array &$attr){
$id = $this->generateId($key, $attr);
$name = $this->generateName($key, $attr);
$value = $this->getValue($key, $attr);
return array($id, $name, $value);
}
}