Completed
Branch master (07b0df)
by judicael
05:36 queued 02:38
created

Form::add()   C

Complexity

Conditions 29
Paths 10

Size

Total Lines 77
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 77
rs 5.0942
cc 29
eloc 48
nc 10
nop 5

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Manage Form
5
 *
6
 * @category  	lib
7
 * @author    	Judicaël Paquet <[email protected]>
8
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
9
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
10
 * @version   	Release: 1.0.0
11
 * @filesource	https://github.com/las93/venus2
12
 * @link      	https://github.com/las93
13
 * @since     	1.0
14
 *
15
 * @tutorial    == in the controller:
16
 *
17
 * 				$this->form
18
 * 					 ->add('task', 'text')
19
 *					 ->add('dueDate', 'date')
20
 *					 ->add('save', 'submit');
21
 *
22
 *				$this->view
23
 *					 ->assign('form', $this->form->getForm())
24
 *					 ->display();
25
 *
26
 *				in the template:
27
 *
28
 *				{$form}
29
 *
30
 *				== if you want test if the form is validated, you could do that:
31
 *
32
 *				if ($this->form->isValid()) { ... } // after the form definition
33
 *
34
 *				== check if the button is clicked:
35
 *
36
 *				if ($this->form->get('save')->isClicked()) { ... }
37
 */
38
namespace Venus\lib;
39
40
use \Attila\lib\Entity          as LibEntity;
41
use \Venus\lib\Form\Checkbox    as Checkbox;
42
use \Venus\lib\Form\Container   as Container;
43
use \Venus\lib\Form\Label       as Label;
44
use \Venus\lib\Form\Input       as Input;
45
use \Venus\lib\Form\Radio       as Radio;
46
use \Venus\lib\Form\Select      as Select;
47
use \Venus\lib\Form\Textarea    as Textarea;
48
49
/**
50
 * This class manage the Form
51
 *
52
 * @category  	lib
53
 * @author    	Judicaël Paquet <[email protected]>
54
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
55
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
56
 * @version   	Release: 1.0.0
57
 * @filesource	https://github.com/las93/venus2
58
 * @link      	https://github.com/las93
59
 * @since     	1.0
60
 */
61
class Form
62
{
63
    /**
64
     * Elements of the form
65
     *
66
     *  @access private
67
     *  @var    array
68
     */
69
    private $_aElement = array();
70
71
    /**
72
     * Increment for form
73
     *
74
     *  @access private
75
     *  @var    int
76
     */
77
    private static $_iFormIncrement = 0;
78
79
    /**
80
     * number of form
81
     *
82
     *  @access private
83
     *  @var    int
84
     */
85
    private $_iFormNumber = 0;
86
87
    /**
88
     * Separator between fields of form
89
     *
90
     *  @access private
91
     *  @var    string
92
     */
93
    private $_sSeparator = '<br/>';
94
95
    /**
96
     * The entity to save with the formular
97
     *
98
     *  @access private
99
     *  @var    string
100
     */
101
    private $_sSynchronizeEntity = null;
102
103
    /**
104
     * The id of entity
105
     *
106
     *  @access private
107
     *  @var    int
108
     */
109
    private $_iIdEntity = null;
110
111
    /**
112
     * The entity to save with the formular
113
     *
114
     *  @access private
115
     *  @var    int
116
     */
117
    private $_iIdEntityCreated = null;
118
119
    /**
120
     * constructor that it increment (static) for all use
121
     *
122
     * @access public
123
     */
124
    public function __construct()
125
    {
126
        self::$_iFormIncrement++;
127
        $this->_iFormNumber = self::$_iFormIncrement;
128
    }
129
130
    /**
131
     * add an element in the form
132
     *
133
     * @access public
134
     * @param  string $sName name
135
     * @param  string|\Venus\lib\Form $mType type of field
136
     * @param  string $sLabel label of field
137
     * @param  mixed $mValue value of field
138
     * @parma  mixed $mOptions options (for select)
139
     * @return \Venus\lib\Form
140
     */
141
    public function add($sName, $mType, $sLabel = null, $mValue = null, $mOptions = null)
142
    {
143
        if ($mType instanceof Container) {
144
145
            $this->_aElement[$sName] = $mType;
146
        } else if ($mType === 'text' || $mType === 'submit' || $mType === 'password' || $mType === 'file' || $mType === 'tel'
147
            || $mType === 'url' || $mType === 'email' || $mType === 'search' || $mType === 'date' || $mType === 'time'
148
            || $mType === 'datetime' || $mType === 'month' || $mType === 'week' || $mType === 'number' || $mType === 'range'
149
            || $mType === 'color') {
150
151
            $this->_aElement[$sName] = new Input($sName, $mType, $sLabel, $mValue);
152
        } elseif ($mType === 'textarea') {
153
154
            $this->_aElement[$sName] = new Textarea($sName, $sLabel, $mValue);
155
        } else  if ($mType === 'select') {
156
157
            $this->_aElement[$sName] = new Select($sName, $mOptions, $sLabel, $mValue);
158
        } else  if ($mType === 'label') {
159
160
            $this->_aElement[$sName] = new Label($sName);
161
        } else  if ($mType === 'list_checkbox') {
162
163
            $i = 0;
164
165
            $this->_aElement[$sName.'_'.$i++] = new Label($sLabel);
166
167
            foreach ($mValue as $mKey => $sValue) {
168
169
                $this->_aElement[$sName.'_'.$i++] = new Checkbox($sName, $sValue, $mKey, $mOptions);
170
            }
171
        } else  if ($mType === 'checkbox') {
172
173
            $this->_aElement[$sName] = new Checkbox($sName, $sLabel, $mValue, $mOptions);
174
        } else  if ($mType === 'radio') {
175
176
            $this->_aElement[$sName.rand(100000, 999999)] = new Radio($sName, $sLabel, $mValue, $mOptions);
177
        } else  if ($mType === 'date') {
178
179
            $aDay = array();
180
181
            for ($i = 1; $i <= 31; $i++) {
182
183
                if ($i < 10) { $aDay['0'.$i] = '0'.$i; }
184
                else { $aDay[$i] = $i; }
185
            }
186
187
            $this->_aElement[$sName.'_day'] = new Select($sName, $aDay);
188
189
            $aMonth = array(
190
                '01' => 'Jan',
191
                '02' => 'Feb',
192
                '03' => 'Mar',
193
                '04' => 'Apr',
194
                '05' => 'May',
195
                '06' => 'Jun',
196
                '07' => 'Jui',
197
                '08' => 'Aug',
198
                '09' => 'Sep',
199
                '10' => 'Oct',
200
                '11' => 'Nov',
201
                '12' => 'Dec',
202
            );
203
204
            $this->_aElement[$sName.'_month'] = new Select($sName, $aMonth);
205
206
            $aYear = array();
207
208
            for ($i = 1900; $i <= 2013; $i++) {
209
210
                $aYear[$i] = $i;
211
            }
212
213
            $this->_aElement[$sName.'_year'] = new Select($sName, $aMonth);
214
        }
215
216
        return $this;
217
    }
218
219
    /**
220
     * get id entity created by the formular
221
     *
222
     * @access public
223
     * @return int
224
     */
225
    public function getIdEntityCreated() : int
226
    {
227
        return $this->_iIdEntityCreated;
228
    }
229
230
    /**
231
     * set id entity created by the formular
232
     *
233
     * @access public
234
     * @param  int $iIdEntityCreated
235
     * @return Form
236
     */
237
    public function setIdEntityCreated(int $iIdEntityCreated) : Form
238
    {
239
        $this->_iIdEntityCreated = $iIdEntityCreated;
240
        return $this;
241
    }
242
243
    /**
244
     * get form number
245
     *
246
     * @access public
247
     * @return int
248
     */
249
    public function getFormNumber() : int
250
    {
251
        return $this->_iFormNumber;
252
    }
253
254
    /**
255
     * set id entity created by the formular
256
     *
257
     * @access public
258
     * @param  int $iFormNumber
259
     * @return Form
260
     */
261
    public function setFormNumber(int $iFormNumber) : Form
262
    {
263
        $this->_iFormNumber = $iFormNumber;
264
        return $this;
265
    }
266
267
    /**
268
     * get global form
269
     *
270
     * @access public
271
     * @return \Venus\lib\Form\Container
272
     */
273
    public function getForm()
274
    {
275
        $oForm = $this->getFormInObject();
276
277
        $sFormContent = $oForm->start;
278
279
        foreach ($oForm->form as $sValue) {
280
281
            $sFormContent .= $sValue.$this->_sSeparator;
282
        }
283
284
        $sFormContent .= $oForm->end;
285
286
        $oContainer = new Container;
287
        $oContainer->setView($sFormContent)
288
                   ->setForm($this);
289
290
        return $oContainer;
291
    }
292
293
294
    /**
295
     * get global object form
296
     *
297
     * @access public
298
     * @return \stdClass
299
     */
300
    public function getFormInObject()
301
    {
302
        if ($this->_iIdEntity > 0 && $this->_sSynchronizeEntity !== null && count($_POST) < 1) {
303
304
            $sModelName = str_replace('Entity', 'Model', $this->_sSynchronizeEntity);
305
            $oModel = new $sModelName;
306
307
            $oEntity = new $this->_sSynchronizeEntity;
308
            $sPrimaryKey = LibEntity::getPrimaryKeyNameWithoutMapping($oEntity);
309
            $sMethodName = 'findOneBy'.$sPrimaryKey;
310
            $oCompleteEntity = call_user_func_array(array(&$oModel, $sMethodName), array($this->_iIdEntity));
311
312
            if (is_object($oCompleteEntity)) {
313
314
                foreach ($this->_aElement as $sKey => $sValue) {
315
316
                    if ($sValue instanceof \Venus\lib\Form\Radio) {
317
318
                        $sExKey = $sKey;
319
                        $sKey = substr($sKey, 0, -6);
320
                    }
321
322
                    if ($sValue instanceof Form) {
323
324
                        ;
325
                    } else {
326
327
                        $sMethodNameInEntity = 'get_'.$sKey;
328
                        $mValue = $oCompleteEntity->$sMethodNameInEntity();
329
330
                        if ($sValue instanceof \Venus\lib\Form\Radio && method_exists($this->_aElement[$sExKey], 'setValueChecked')) {
331
332
                            $this->_aElement[$sExKey]->setValueChecked($mValue);
0 ignored issues
show
Bug introduced by
The variable $sExKey does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
333
                        } else if (isset($mValue) && method_exists($this->_aElement[$sKey], 'setValue')) {
334
335
                            $this->_aElement[$sKey]->setValue($mValue);
336
                        }
337
                    }
338
                }
339
            }
340
        }
341
342
        $oForm = new \StdClass();
343
        $oForm->start = '<form name="form'.$this->_iFormNumber.'" method="post"><input type="hidden" value="1" name="validform'.$this->_iFormNumber.'">';
344
        $oForm->form = array();
345
346
        foreach ($this->_aElement as $sKey => $sValue) {
347
348
            if ($sValue instanceof Container) {
349
350
                $oForm->form[$sKey] = $sValue;
351
            } else {
352
353
                $oForm->form[$sKey] = $sValue->fetch();
354
            }
355
        }
356
357
        $oForm->end = '</form>';
358
359
        return $oForm;
360
    }
361
362
    /**
363
     * get an element of formular
364
     *
365
     * @access public
366
     * @param  string $sName name
367
     * @return object
368
     */
369
    public function get($sName)
370
    {
371
        return $this->_aElement[$sName];
372
    }
373
374
    /**
375
     * get the form separator
376
     *
377
     * @access public
378
     * @return string
379
     */
380
    public function getSeparator()
381
    {
382
        return $this->_sSeparator;
383
    }
384
385
    /**
386
     * set the form separator
387
     *
388
     * @access public
389
     * @param  string $sSeparator separator between the fields
390
     * @return \Venus\lib\Form
391
     */
392
    public function setSeparator($sSeparator)
393
    {
394
        $this->_sSeparator = $sSeparator;
395
        return $this;
396
    }
397
398
    /**
399
     * set the entity to synchronize with the formular
400
     *
401
     * @access public
402
     * @param $sSynchronizeEntity
403
     * @param  int $iId id of the primary key
404
     * @return Form
405
     * @internal param string $sSeparator separator between the fields
406
     */
407
    public function synchronizeEntity($sSynchronizeEntity, $iId = null)
408
    {
409
        if ($iId !== null) { $this->_iIdEntity = $iId; }
410
411
        $this->_sSynchronizeEntity = $sSynchronizeEntity;
412
        return $this;
413
    }
414
415
    /**
416
     * add constraint
417
     *
418
     * @access public
419
     * @param  string $sName field name
420
     * @param  object $oConstraint constraint on the field
421
     * @return \Venus\lib\Form
422
     */
423
    public function addConstraint($sName, $oConstraint)
424
    {
425
        if ($this->_aElement[$sName] instanceof Input || $this->_aElement[$sName] instanceof Textarea) {
426
427
            $this->_aElement[$sName]->setConstraint($oConstraint);
428
        }
429
430
        return $this;
431
    }
432
433
    /**
434
     * get all elements
435
     *
436
     * @access public
437
     * @return  array
438
     */
439
    public function getElement() {
440
441
        return $this->_aElement;
442
    }
443
444
    /**
445
     * get all elements
446
     *
447
     * @access public
448
     * @return int
449
     */
450
    public function getIdEntity() {
451
452
        return $this->_iIdEntity;
453
    }
454
455
    /**
456
     * get all elements
457
     *
458
     * @access public
459
     * @return string
460
     */
461
    public function getSynchronizeEntity() {
462
463
        return $this->_sSynchronizeEntity;
464
    }
465
}
466