Completed
Pull Request — master (#588)
by
unknown
14:32
created

Checkbox::defaultRender()   D

Complexity

Conditions 12
Paths 320

Size

Total Lines 54
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 12

Importance

Changes 0
Metric Value
cc 12
eloc 37
nc 320
nop 0
dl 0
loc 54
ccs 37
cts 37
cp 1
crap 12
rs 4.6333
c 0
b 0
f 0

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
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
namespace Xoops\Form;
13
14
/**
15
 * Checkbox - a checkbox form element
16
 *
17
 * @category  Xoops\Form\Checkbox
18
 * @package   Xoops\Form
19
 * @author    Kazumi Ono <[email protected]>
20
 * @author    Skalpa Keo <[email protected]>
21
 * @author    Taiwen Jiang <[email protected]>
22
 * @copyright 2001-2016 XOOPS Project (http://xoops.org)
23
 * @license   GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
24
 * @link      http://xoops.org
25
 */
26
class Checkbox extends OptionElement
27
{
28
    /**
29
     * pre-selected values in array
30
     *
31
     * @var array
32
     */
33
    protected $value = array();
34
35
    /**
36
     * Constructor
37
     *
38
     * @param string|array $caption Caption or array of all attributes
39
     *                               Control attributes:
40
     *                                   :inline true to render with inline style
41
     * @param string       $name    element name
42
     * @param mixed        $value   value(s) to be set on display, either one value or an array of them.
43
     * @param boolean      $inline  true for inline arrangement
44
     */
45 7
    public function __construct($caption, $name = null, $value = null, $inline = true)
46
    {
47 7
        if (is_array($caption)) {
48 3
            parent::__construct($caption);
49 3
            $this->setIfNotSet(':inline', true);
50
        } else {
51 5
            parent::__construct([]);
52 5
            $this->setWithDefaults('caption', $caption, '');
53 5
            $this->setWithDefaults('name', $name, 'name_error');
54 5
            $this->set('value', $value);
55 5
            $this->set(':inline', $inline);
56
        }
57 7
        $this->set('type', 'checkbox');
58 7
    }
59
60
    /**
61
     * defaultRender
62
     *
63
     * @return string rendered form element
64
     */
65 3
    public function defaultRender()
66
    {
67 3
        $required = $this->has('required');
68 3
        $elementOptions = $this->getOptions();
69 3
        $elementValue = $this->getValue();
70 3
        if (!is_array($elementValue)) {
71 3
            $elementValue = (array) $elementValue;
72
        }
73 3
        $extra = ($this->getExtra() != '' ? " " . $this->getExtra() : '');
74
75 3
        $elementName = $this->getName();
76 3
        $elementId = $elementName;
77 3
        if (count($elementOptions) > 1 && substr($elementName, -2, 2) !== '[]') {
78 2
            $elementName = $elementName . '[]';
79 2
            $this->setName($elementName);
80
            // If required is set, all checkboxes will be required by the browser,
81
            // which is not usually useful. We stash the value of required above
82
            // and unset now. We restore it before return so JS validation will still
83
            // be triggered. This is only a problem if there is more than one checkbox.
84 2
            $this->remove('required');
85
        }
86
87 3
        $ret = "";
88 3
        $inline = (bool) $this->get(':inline', false);
89 3
        if ($inline) {
90 2
            $ret .= '<div class="input-group">';
91
        }
92 3
        $idCount = 0;
93 3
        foreach ($elementOptions as $value => $name) {
94 2
            $this->remove('checked');
95 2
            if (!empty($elementValue) && in_array($value, $elementValue)) {
0 ignored issues
show
Bug introduced by
It seems like $elementValue can also be of type string; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

95
            if (!empty($elementValue) && in_array($value, /** @scrutinizer ignore-type */ $elementValue)) {
Loading history...
96 1
                $this->set('checked');
97
            }
98 2
            $this->set('value', $value);
99 2
            ++$idCount;
100 2
            $this->set('id', $elementId . $idCount);
101 2
            if ($inline) {
102 1
                $ret .= '<label class="checkbox-inline">';
103 1
                $ret .= '<input ' . $this->renderAttributeString() . $extra . ">" . $name . "\n";
104 1
                $ret .= "</label>\n";
105
            } else {
106 1
                $ret .= "<div class=\"checkbox\">\n<label>";
107 1
                $ret .= '<input ' . $this->renderAttributeString() . $extra . '>' . $name . "\n";
108 2
                $ret .= "</label>\n</div>\n";
109
            }
110
111
        }
112 3
        if ($required) {
113 1
            $this->set('required');
114
        }
115 3
        if ($inline) {
116 2
            $ret .= '</div>';
117
        }
118 3
        return $ret;
119
    }
120
121
    /**
122
     * Render custom javascript validation code
123
     *
124
     * @return string
125
     */
126 2
    public function renderValidationJS()
127
    {
128
        // render custom validation code if any
129 2
        if (!empty($this->customValidationCode)) {
130
            return implode("\n", $this->customValidationCode);
131
            // generate validation code if required
132 2
        } elseif ($this->isRequired()) {
133 1
            $eltname = $this->getName();
134 1
            $eltcaption = $this->getCaption();
135 1
            $eltmsg = empty($eltcaption)
136
                ? sprintf(\XoopsLocale::F_ENTER, $eltname)
137 1
                : sprintf(\XoopsLocale::F_ENTER, $eltcaption);
138 1
            $eltmsg = str_replace('"', '\"', stripslashes($eltmsg));
139
            return "\n"
140 1
            . "var hasChecked = false; var checkBox = myform.elements['{$eltname}'];"
141 1
            . " if (checkBox.length) {for (var i = 0; i < checkBox.length; i++)"
142 1
            . " {if (checkBox[i].checked == true) {hasChecked = true; break;}}}"
143 1
            . "else{if (checkBox.checked == true) {hasChecked = true;}}"
144 1
            . "if (!hasChecked) {window.alert(\"{$eltmsg}\");if (checkBox.length)"
145 1
            . " {checkBox[0].focus();}else{checkBox.focus();}return false;}";
146
        }
147 1
        return '';
148
    }
149
}
150