Completed
Push — master ( dca322...47e653 )
by Julito
08:54
created

HTML_QuickForm_select   F

Complexity

Total Complexity 95

Size/Duplication

Total Lines 610
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 205
dl 0
loc 610
rs 2
c 0
b 0
f 0
wmc 95

How to fix   Complexity   

Complex Class

Complex classes like HTML_QuickForm_select often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use HTML_QuickForm_select, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Class to dynamically create an HTML SELECT
5
 *
6
 * PHP versions 4 and 5
7
 *
8
 * LICENSE: This source file is subject to version 3.01 of the PHP license
9
 * that is available through the world-wide-web at the following URI:
10
 * http://www.php.net/license/3_01.txt If you did not receive a copy of
11
 * the PHP License and are unable to obtain it through the web, please
12
 * send a note to [email protected] so we can mail you a copy immediately.
13
 *
14
 * @category    HTML
15
 * @package     HTML_QuickForm
16
 * @author      Adam Daniel <[email protected]>
17
 * @author      Bertrand Mansion <[email protected]>
18
 * @author      Alexey Borzov <[email protected]>
19
 * @copyright   2001-2009 The PHP Group
20
 * @license     http://www.php.net/license/3_01.txt PHP License 3.01
21
 * @version     CVS: $Id: select.php,v 1.34 2009/04/04 21:34:04 avb Exp $
22
 * @link        http://pear.php.net/package/HTML_QuickForm
23
 */
24
25
/**
26
 * Class to dynamically create an HTML SELECT
27
 *
28
 * @category    HTML
29
 * @package     HTML_QuickForm
30
 * @author      Adam Daniel <[email protected]>
31
 * @author      Bertrand Mansion <[email protected]>
32
 * @author      Alexey Borzov <[email protected]>
33
 * @version     Release: 3.2.11
34
 * @since       1.0
35
 */
36
class HTML_QuickForm_select extends HTML_QuickForm_element
37
{
38
    /**
39
     * Contains the select options
40
     *
41
     * @var       array
42
     * @since     1.0
43
     * @access    private
44
     */
45
    protected $_options = array();
46
    private $_optgroups = array();
47
48
    /**
49
     * Default values of the SELECT
50
     *
51
     * @var       array
52
     * @since     1.0
53
     * @access    private
54
     */
55
    protected $_values = [];
56
57
    /**
58
     * Class constructor
59
     *
60
     * @param     string    $elementName Select name attribute
61
     * @param     mixed     $elementLabel Label(s) for the select
62
     * @param     mixed     $options Data to be used to populate options
63
     * @param     mixed     $attributes Either a typical HTML attribute string or an associative array
64
     * @since     1.0
65
     * @access    public
66
     */
67
    public function __construct(
68
        $elementName,
69
        $elementLabel = '',
70
        $options = null,
71
        $attributes = null
72
    ) {
73
        $addBlank = '';
74
        if (is_array($attributes) || empty($attributes)) {
75
            $oldClass = '';
76
            if (!empty($attributes['class'])) {
77
                $oldClass = $attributes['class'];
78
            }
79
            if (empty($attributes)) {
80
                $attributes = []; // Initialize variable to avoid warning in PHP 7.1
81
            }
82
            $attributes['class'] = $oldClass . 'form-control selectpicker show-tick ';
83
            $attributes['data-style'] = 'custom-select';
84
            $attributes['data-live-search'] = 'true';
85
86
            if (isset($attributes['disable_js']) && $attributes['disable_js']) {
87
                $attributes['class'] = 'form-control';
88
                $attributes['data-live-search'] = '';
89
            }
90
91
            if (isset($attributes['extra_class']) && $attributes['extra_class']) {
92
                $attributes['class'] .= ' '.$attributes['extra_class'];
93
                unset($attributes['extra_class']);
94
            }
95
96
            if (isset($attributes['placeholder'])) {
97
                $addBlank =  $attributes['placeholder'];
98
            }
99
        }
100
        $columnsSize = isset($attributes['cols-size']) ? $attributes['cols-size'] : null;
101
        $this->setColumnsSize($columnsSize);
102
        $icon = isset($attributes['icon']) ? $attributes['icon'] : null;
103
        $this->setIcon($icon);
104
        if (!empty($icon)) {
105
            unset($attributes['icon']);
106
        }
107
        parent::__construct($elementName, $elementLabel, $attributes);
108
        $this->_persistantFreeze = true;
109
        $this->_type = 'select';
110
111
        if ($addBlank !== '') {
112
            if (isset($options)) {
113
                $options = ['' => $addBlank] + $options;
114
            } else {
115
                $options = ['' => $addBlank];
116
            }
117
        }
118
        if (isset($options)) {
119
            $this->load($options);
120
        }
121
    }
122
123
     /**
124
     * Loads options from different types of data sources
125
     *
126
     * This method is a simulated overloaded method.  The arguments, other than the
127
     * first are optional and only mean something depending on the type of the first argument.
128
     * If the first argument is an array then all arguments are passed in order to loadArray.
129
     * If the first argument is a db_result then all arguments are passed in order to loadDbResult.
130
     * If the first argument is a string or a DB connection then all arguments are
131
     * passed in order to loadQuery.
132
     * @param     mixed     $options     Options source currently supports assoc array or DB_result
133
     * @param     mixed     $param1     (optional) See function detail
134
     * @param     mixed     $param2     (optional) See function detail
135
     * @param     mixed     $param3     (optional) See function detail
136
     * @param     mixed     $param4     (optional) See function detail
137
     * @since     1.1
138
     * @access    public
139
     * @return    PEAR_Error on error or true
140
     * @throws    PEAR_Error
141
     */
142
    protected function load(&$options, $param1=null, $param2=null, $param3=null, $param4=null)
143
    {
144
        switch (true) {
145
            case is_array($options):
146
                return $this->loadArray($options, $param1);
147
                break;
148
        }
149
    }
150
151
    /**
152
     * Loads the options from an associative array
153
     *
154
     * @param     array    $arr     Associative array of options
155
     * @param     mixed    $values  (optional) Array or comma delimited string of selected values
156
     * @since     1.0
157
     * @access    public
158
     * @return    PEAR_Error on error or true
159
     * @throws    PEAR_Error
160
     */
161
    private function loadArray($arr, $values = null)
162
    {
163
        if (!is_array($arr)) {
164
            return false;
165
        }
166
        if (isset($values)) {
167
            $this->setSelected($values);
168
        }
169
        foreach ($arr as $key => $val) {
170
            // Fix in order to use list of entities.
171
            if (is_object($val)) {
172
                $key = $val->getId();
173
                $val = $val->__toString();
174
            }
175
176
            // Warning: new API since release 2.3
177
            $this->addOption($val, $key);
178
        }
179
        return true;
180
    }
181
182
    /**
183
     * Returns the current API version
184
     *
185
     * @since     1.0
186
     * @access    public
187
     * @return    double
188
     */
189
    function apiVersion()
190
    {
191
        return 2.3;
192
    }
193
194
    /**
195
     * Sets the default values of the select box
196
     *
197
     * @param     mixed    $values  Array or comma delimited string of selected values
198
     * @since     1.0
199
     * @access    public
200
     * @return    void
201
     */
202
    function setSelected($values)
203
    {
204
        if (is_string($values) && $this->getMultiple()) {
205
            $values = explode('[ ]?,[ ]?', $values);
206
        }
207
        if (is_array($values)) {
208
            $this->_values = array_values($values);
209
        } else {
210
            $this->_values = array($values);
211
        }
212
    }
213
214
    /**
215
     * Sets the input field name
216
     *
217
     * @param     string    $name   Input field name attribute
218
     * @since     1.0
219
     * @access    public
220
     * @return    void
221
     */
222
    function setName($name)
223
    {
224
        $this->updateAttributes(array('name' => $name));
225
    }
226
227
    /**
228
     * Returns the element name
229
     *
230
     * @since     1.0
231
     * @access    public
232
     * @return    string
233
     */
234
    function getName()
235
    {
236
        return $this->getAttribute('name');
237
    }
238
239
    /**
240
     * Returns the element name (possibly with brackets appended)
241
     *
242
     * @since     1.0
243
     * @access    public
244
     * @return    string
245
     */
246
    function getPrivateName()
247
    {
248
        if ($this->getAttribute('multiple')) {
249
            return $this->getName() . '[]';
250
        } else {
251
            return $this->getName();
252
        }
253
    }
254
255
    /**
256
     * Sets the value of the form element
257
     *
258
     * @param     mixed    $values  Array or comma delimited string of selected values
259
     * @since     1.0
260
     * @access    public
261
     * @return    void
262
     */
263
    function setValue($value)
264
    {
265
        $this->setSelected($value);
266
    }
267
268
    /**
269
     * Returns an array of the selected values
270
     *
271
     * @since     1.0
272
     * @access    public
273
     * @return    array of selected values
274
     */
275
    function getValue()
276
    {
277
        return $this->_values;
278
    }
279
280
    /**
281
     * Sets the select field size, only applies to 'multiple' selects
282
     *
283
     * @param     int    $size  Size of select  field
284
     * @since     1.0
285
     * @access    public
286
     * @return    void
287
     */
288
    function setSize($size)
289
    {
290
        $this->updateAttributes(array('size' => $size));
291
    }
292
293
    /**
294
     * Returns the select field size
295
     *
296
     * @since     1.0
297
     * @access    public
298
     * @return    int
299
     */
300
    function getSize()
301
    {
302
        return $this->getAttribute('size');
303
    }
304
305
    /**
306
     * Sets the select mutiple attribute
307
     *
308
     * @param     bool    $multiple  Whether the select supports multi-selections
309
     * @since     1.2
310
     * @access    public
311
     * @return    void
312
     */
313
    function setMultiple($multiple)
314
    {
315
        if ($multiple) {
316
            $this->updateAttributes(array('multiple' => 'multiple'));
317
        } else {
318
            $this->removeAttribute('multiple');
319
        }
320
    }
321
322
    /**
323
     * Returns the select mutiple attribute
324
     *
325
     * @since     1.2
326
     * @access    public
327
     * @return    bool    true if multiple select, false otherwise
328
     */
329
    function getMultiple()
330
    {
331
        return (bool)$this->getAttribute('multiple');
332
    }
333
334
    /**
335
     * Adds a new OPTION to the SELECT
336
     *
337
     * @param     string    $text       Display text for the OPTION
338
     * @param     string    $value      Value for the OPTION
339
     * @param     mixed     $attributes Either a typical HTML attribute string
340
     *                                  or an associative array
341
     * @since     1.0
342
     * @access    public
343
     * @return    void
344
     */
345
    function addOption($text, $value, $attributes = null, $return_array = false)
346
    {
347
        if (null === $attributes) {
348
            $attributes = array('value' => (string)$value);
349
        } else {
350
            $attributes = $this->_parseAttributes($attributes);
351
            if (isset($attributes['selected'])) {
352
                // the 'selected' attribute will be set in toHtml()
353
                $this->_removeAttr('selected', $attributes);
354
                if (is_null($this->_values)) {
355
                    $this->_values = array($value);
356
                } elseif (!in_array($value, $this->_values)) {
357
                    $this->_values[] = $value;
358
                }
359
            }
360
            $this->_updateAttrArray($attributes, array('value' => (string)$value));
361
        }
362
        if ($return_array) {
363
            return array('text' => $text, 'attr' => $attributes);
364
        } else {
365
            $this->_options[] = array('text' => $text, 'attr' => $attributes);
366
        }
367
    }
368
369
    /**
370
     * Adds a new OPTION to the SELECT
371
     *
372
     * @param     string    $text       Display text for the OPTION
373
     * @param     string    $value      Value for the OPTION
374
     * @param     mixed     $attributes Either a typical HTML attribute string
375
     *                                  or an associative array
376
     * @since     1.0
377
     * @access    public
378
     * @return    void
379
     */
380
    function addOptGroup($options, $label)
381
    {
382
        foreach ($options as $option) {
383
            $this->addOption($option['text'], $option['value'], $option, true);
384
        }
385
        $this->_optgroups[] = array('label' => $label, 'options' => $options);
386
    }
387
388
    /**
389
     * Returns the SELECT in HTML
390
     *
391
     * @since     1.0
392
     * @access    public
393
     * @return    string
394
     */
395
    public function toHtml()
396
    {
397
        if ($this->_flagFrozen) {
398
            return $this->getFrozenHtml();
399
        } else {
400
            $tabs    = $this->_getTabs();
401
402
            $strHtml = '';
403
404
            if ($this->getComment() != '') {
405
                $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
406
            }
407
408
            if (!$this->getMultiple()) {
409
                $attrString = $this->_getAttrString($this->_attributes);
410
            } else {
411
                $myName = $this->getName();
412
                $this->setName($myName . '[]');
413
                $attrString = $this->_getAttrString($this->_attributes);
414
                $this->setName($myName);
415
            }
416
417
            $strHtml .= $tabs . '<select ' . $attrString . ">\n";
418
            $strValues = is_array($this->_values)? array_map('strval', $this->_values): array();
419
420
            foreach ($this->_options as $option) {
421
                if (!empty($strValues) && in_array($option['attr']['value'], $strValues, true)) {
422
                    $option['attr']['selected'] = 'selected';
423
                }
424
                $strHtml .= $tabs . "<option" . $this->_getAttrString($option['attr']) . '>' .
425
                    $option['text'] . "</option>";
426
            }
427
            foreach ($this->_optgroups as $optgroup) {
428
                $strHtml .= $tabs . '<optgroup label="' . $optgroup['label'] . '">';
429
                foreach ($optgroup['options'] as $option) {
430
                    $text = $option['text'];
431
                    unset($option['text']);
432
433
                    if (!empty($strValues) && in_array($option['value'], $strValues)) {
434
                        $option['selected'] = 'selected';
435
                    }
436
437
                    $strHtml .= $tabs . " <option" . $this->_getAttrString($option) . '>' .$text . "</option>";
438
                }
439
                $strHtml .= "</optgroup>";
440
            }
441
            return $strHtml . $tabs . '</select>';
442
        }
443
    }
444
445
    /**
446
     * Returns the value of field without HTML tags
447
     *
448
     * @since     1.0
449
     * @access    public
450
     * @return    string
451
     */
452
    function getFrozenHtml()
453
    {
454
        $value = array();
455
        if (is_array($this->_values)) {
456
            foreach ($this->_values as $key => $val) {
457
                for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
458
                    if (0 == strcmp($val, $this->_options[$i]['attr']['value'])) {
459
                        $value[$key] = $this->_options[$i]['text'];
460
                        break;
461
                    }
462
                }
463
            }
464
        }
465
        $html = empty($value)? '&nbsp;': join('<br />', $value);
466
        if ($this->_persistantFreeze) {
467
            $name = $this->getPrivateName();
468
            // Only use id attribute if doing single hidden input
469
            if (1 == count($value)) {
470
                $id     = $this->getAttribute('id');
471
                $idAttr = isset($id)? array('id' => $id): array();
472
            } else {
473
                $idAttr = array();
474
            }
475
            foreach ($value as $key => $item) {
476
                $html .= '<input' . $this->_getAttrString(array(
477
                             'type'  => 'hidden',
478
                             'name'  => $name,
479
                             'value' => $this->_values[$key]
480
                         ) + $idAttr) . ' />';
481
            }
482
        }
483
        return $html;
484
    }
485
486
   /**
487
    * We check the options and return only the values that _could_ have been
488
    * selected. We also return a scalar value if select is not "multiple"
489
    */
490
    function exportValue(&$submitValues, $assoc = false)
491
    {
492
        $value = $this->_findValue($submitValues);
493
        if (is_null($value)) {
494
            $value = $this->getValue();
495
        } elseif(!is_array($value)) {
496
            $value = array($value);
497
        }
498
        if (is_array($value) && !empty($this->_options)) {
499
            $cleanValue = null;
500
            foreach ($value as $v) {
501
                for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
502
                    if (0 == strcmp($v, $this->_options[$i]['attr']['value'])) {
503
                        $cleanValue[] = $v;
504
                        break;
505
                    }
506
                }
507
            }
508
        } else {
509
            $cleanValue = $value;
510
        }
511
        if (is_array($cleanValue) && !$this->getMultiple()) {
512
            return $this->_prepareValue($cleanValue[0], $assoc);
513
        } else {
514
            return $this->_prepareValue($cleanValue, $assoc);
515
        }
516
    }
517
518
    function onQuickFormEvent($event, $arg, &$caller)
519
    {
520
        if ('updateValue' == $event) {
521
            $value = $this->_findValue($caller->_constantValues);
522
            if (null === $value) {
523
                $value = $this->_findValue($caller->_submitValues);
524
                // Fix for bug #4465 & #5269
525
                // XXX: should we push this to element::onQuickFormEvent()?
526
                if (null === $value && (!$caller->isSubmitted() || !$this->getMultiple())) {
527
                    $value = $this->_findValue($caller->_defaultValues);
528
                }
529
            }
530
            if (null !== $value) {
531
                $this->setValue($value);
532
            }
533
            return true;
534
        } else {
535
            return parent::onQuickFormEvent($event, $arg, $caller);
536
        }
537
    }
538
539
    /**
540
     * @param FormValidator $form
541
     */
542
    public function updateSelectWithSelectedOption(FormValidator $form)
543
    {
544
        $id = $this->getAttribute('id');
545
        $form->addHtml('<script>
546
                $(function(){
547
                    var optionClass = $("#'.$id.'").find("option:checked").attr("class"); 
548
                    $("#'.$id.'").attr("class", "form-control " + optionClass);                    
549
                    $("#'.$id.'").on("change", function() {
550
                        var optionClass = ($(this).find("option:checked").attr("class")); 
551
                        $(this).attr("class", "form-control " + optionClass);
552
                    });
553
                });
554
            </script>');
555
    }
556
557
    /**
558
     * Show an icon at the left side of an input
559
     * @return string
560
     */
561
    public function getIconToHtml()
562
    {
563
        $icon = $this->getIcon();
564
        $isButton = $this->getButton();
565
566
        if (empty($icon)) {
567
            return '';
568
        }
569
        $element = '<span class="input-group-text"><em class="fa fa-' . $icon . '"></em></span>';
570
571
        if ($isButton) {
572
            $element = '<button class="btn btn-outline-secondary" type="reset">
573
                            <em class="fa fa-' . $icon . '"></em>
574
                        </button>';
575
        }
576
577
        return '<div class="input-group-append">
578
                    ' . $element . '
579
                </div>';
580
    }
581
582
    /**
583
     * @param string $layout
584
     *
585
     * @return string
586
     */
587
    public function getTemplate($layout)
588
    {
589
        $size = $this->calculateSize();
590
591
        switch ($layout) {
592
            case FormValidator::LAYOUT_INLINE:
593
                return '
594
                    <label class="sr-only" {label-for} >
595
                        <!-- BEGIN required --><span class="form_required">*</span><!-- END required -->
596
                        {label}
597
                    </label>                            
598
                    {element}
599
                ';
600
                break;
601
            case FormValidator::LAYOUT_HORIZONTAL:
602
                return '
603
                <div class="form-group row {error_class}">
604
                    <label {label-for}  class="col-sm-'.$size[0].' col-form-label {extra_label_class}" >
605
                        <!-- BEGIN required --><span class="form_required">*</span><!-- END required -->
606
                        {label}
607
                    </label>
608
                    <div class="col-sm-'.$size[1].'">
609
                        {icon}
610
                        {element}
611
612
                        <!-- BEGIN label_2 -->
613
                            <p class="help-block">{label_2}</p>
614
                        <!-- END label_2 -->
615
616
                        <!-- BEGIN error -->
617
                            <span class="help-inline help-block">{error}</span>
618
                        <!-- END error -->
619
                    </div>
620
                    <div class="col-sm-'.$size[2].'">
621
                        <!-- BEGIN label_3 -->
622
                            {label_3}
623
                        <!-- END label_3 -->
624
                    </div>
625
                </div>';
626
                break;
627
            case FormValidator::LAYOUT_BOX_NO_LABEL:
628
                return '
629
                        <div class="input-group">
630
                            {icon}
631
                            {element}
632
                        </div>';
633
            case FormValidator::LAYOUT_BOX_SEARCH:
634
                return '
635
                        <div class="form-group row">
636
                            <label class="col-sm-2 col-form-label" {label-for}>{label}</label>
637
                            <div class="col-sm-8">
638
                                <div class="input-group">
639
                                    {element}
640
                                    {icon}
641
                                </div>
642
                            </div>
643
                            <div class="col-sm-2"></div>
644
                        </div>';
645
                break;
646
        }
647
    }
648
}
649