Select::render()   C
last analyzed

Complexity

Conditions 10
Paths 64

Size

Total Lines 47
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 21
c 0
b 0
f 0
nc 64
nop 0
dl 0
loc 47
rs 5.1578

How to fix   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
 * Koch Framework
5
 * Jens-André Koch © 2005 - onwards.
6
 *
7
 * This file is part of "Koch Framework".
8
 *
9
 * License: GNU/GPL v2 or any later version, see LICENSE file.
10
 *
11
 * This program is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 2 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace Koch\Form\Elements;
26
27
use Koch\Form\FormElement;
28
use Koch\Form\FormElementInterface;
29
30
/**
31
 *
32
 */
33
class Select extends FormElement implements FormElementInterface
34
{
35
    /**
36
     * @var array array with options for the dropdown
37
     */
38
    public $options;
39
40
    /**
41
     * @var string name of the default option of the select dropdown (pre-selection)
42
     */
43
    public $default;
44
45
    /**
46
     * @var string description
47
     */
48
    public $description;
49
50
    /**
51
     * 0 = pure dropdown with 1 field
52
     * 3 = 3 elements shown, rest available via scrollbar.
53
     *
54
     * @var int number of displayed items
55
     */
56
    public $size;
57
58
    public $withValuesAsKeys;
59
60
    /**
61
     * @var string Label
62
     */
63
    #public $label ='Select an item from this pull-down menu.';
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
64
65
    public function __construct()
66
    {
67
        $this->type = 'select';
68
    }
69
70
    /**
71
     * Sets the array with options for the dropdown element.
72
     *
73
     * @param array $options
74
     * @param bool  $addSelectText Adds " - Select -" as first entry to the options array.
75
     *
76
     * @return Select
77
     */
78
    public function setOptions($options, $addSelectText = true)
79
    {
80
        if ($addSelectText === true) {
81
            // add one entry on top for the dropdown
82
            array_unshift($options, _('Select...'));
83
        }
84
85
        $this->options = $options;
86
87
        return $this;
88
    }
89
90
    public function setSize($size)
91
    {
92
        $this->size = $size;
93
94
        return $this;
95
    }
96
97
    /**
98
     * This sets the default value.
99
     * Value is used to mark that option as "selected".
100
     */
101
    public function setDefaultValue($default)
102
    {
103
        $this->default = $default;
104
105
        return $this;
106
    }
107
108
    /**
109
     * Render option tags with value => value relation.
110
     *
111
     * <option value="' . $value. '">' . $value . '</option>
112
     *
113
     * and not as a key => value relation
114
     *
115
     * <option value="' . $key . '">' . $value . '</option>
116
     *
117
     * This makes it a bit easier to pass actual values around via POST,
118
     * instead of passing the numeric index for lookup.
119
     *
120
     * @return Select \Koch\Form\Element\Select
121
     */
122
    public function withValuesAsKeys()
123
    {
124
        $this->withValuesAsKeys = true;
125
126
        return $this;
127
    }
128
129
    public function render()
130
    {
131
        // open the html select tag
132
        $html = '';
133
        $html .= '<select ';
134
        $html .= (bool) $this->name ? 'name="' . $this->name . '"' : null;
135
        $html .= (bool) $this->id ? 'id="' . $this->id . '"' : null;
136
        $html .= (bool) $this->class ? 'class="' . $this->class . '"' : null;
137
        $html .= (bool) $this->size ? 'size="' . $this->size . '"' : null;
138
        $html .= '>';
139
140
        /**
141
         * This handles the default value setting via the options array key "selected".
142
         * It grabs the first element in the options array, which keyname should be 'selected'
143
         * and then removes it, setting its value to $this->default.
144
         *
145
         * The check for empty($this->default) is important, because the default value might already
146
         * be set via setDefaultValue(). Such a scenario is given, when the form is generated via array.
147
         * The array would contain options['selected'] with an default value, but the actual default
148
         * value is incomming via setDefaultValue().
149
         *
150
         * Note: If the options array is incomming via a formgenerator: the generator has already performed this step!
151
         * $this->setDefault(options['selected']);
152
         */
153
        if ($this->options['selected'] !== null and empty($this->default)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
154
            $this->default = $this->options['selected'];
155
            unset($this->options['selected']);
156
        }
157
158
        if (empty($this->options) === false) {
159
            // loop over all selectfield options
160
            foreach ($this->options as $key => $value) {
161
                if ($this->withValuesAsKeys === true) {
162
                    $html .= $this->renderOptionTag($value, $value);
163
                } else {
164
                    $html .= $this->renderOptionTag($key, $value);
165
                }
166
            }
167
        } else {
168
            $html .= '<option value="0">No Options given.</option>';
169
        }
170
171
        // close the html select tag
172
        $html .= '</select>';
173
174
        return $html;
175
    }
176
177
    private function renderOptionTag($key, $value)
178
    {
179
        /*
180
         * the addSelectText would be posted as value.
181
         * in order to be able to use empty() on the incomming post array variables,
182
         * we need to remove it. this makes it just a select helper, without data.
183
         */
184
        if ($key === 'Select...') {
185
            $key = '';
186
        }
187
188
        // check if the value is the default one and in case it is, add html "selected"
189
        if ($key === $this->default) {
190
            return '<option value="' . $key . '" selected="selected">' . $value . '</option>';
191
        } else { // a normal select element is rendered
192
193
            return '<option value="' . $key . '">' . $value . '</option>';
194
        }
195
    }
196
}
197