ComboBoxWidget::getComboBox()   C
last analyzed

Complexity

Conditions 13
Paths 36

Size

Total Lines 50
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 30
nc 36
nop 2
dl 0
loc 50
rs 5.3808
c 1
b 0
f 0

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 25 and the first side effect is on line 7.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
namespace DigitalWand\AdminHelper\Widget;
4
5
use Bitrix\Main\Localization\Loc;
6
7
Loc::loadMessages(__FILE__);
8
9
/**
10
 * Выпадающий список.
11
 *
12
 * Доступные опции:
13
 * <ul>
14
 * <li> STYLE - inline-стили</li>
15
 * <li> VARIANTS - массив с вариантами значений или функция для их получения в формате ключ=>заголовок
16
 *        Например:
17
 *            [
18
 *                1=>'Первый пункт',
19
 *                2=>'Второй пункт'
20
 *            ]
21
 * </li>
22
 * <li> DEFAULT_VARIANT - ID варианта по-умолчанию</li>
23
 * </ul>
24
 */
25
class ComboBoxWidget extends HelperWidget
26
{
27
    static protected $defaults = array(
28
        'EDIT_IN_LIST' => true
29
    );
30
31
    /**
32
     * @inheritdoc
33
     *
34
     * @see AdminEditHelper::showField();
35
     *
36
     * @param bool $forFilter
0 ignored issues
show
Bug introduced by
There is no parameter named $forFilter. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
37
     *
38
     * @return mixed
39
     */
40
    protected function getEditHtml()
41
    {
42
        return $this->getComboBox();
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    protected function getMultipleEditHtml()
49
    {
50
        return $this->getComboBox(true);
51
    }
52
53
    /**
54
     * Возвращает ХТМЛ-код с комбобоксом.
55
     *
56
     * @param bool $multiple Множественный режим.
57
     * @param bool $forFilter Комбобокс будет выводиться в блоке с фильтром.
58
     *
59
     * @return string
60
     */
61
    protected function getComboBox($multiple = false, $forFilter = false)
62
    {
63
        if ($multiple) {
64
            $value = $this->getMultipleValue();
65
        } else {
66
            $value = $this->getValue();
67
        }
68
69
        $style = $this->getSettings('STYLE');
70
71
        $variants = $this->getVariants();
72
73
        if (!$multiple)
74
        {
75
            array_unshift($variants, array(
76
                'ID' => null,
77
                'TITLE' => null
78
            ));
79
        }
80
81
        if (empty($variants)) {
82
            $comboBox = Loc::getMessage('DIGITALWAND_AH_MISSING_VARIANTS');
83
        } else {
84
            $name = $forFilter ? $this->getFilterInputName() : $this->getEditInputName();
85
            $comboBox = '<select name="' . $name . ($multiple ? '[]' : null) . '"
86
                '. ($multiple ? 'multiple="multiple"' : null) . '
87
                style="' . $style . '">';
88
89
            foreach ($variants as $variant) {
90
                $selected = false;
91
92
                if ($variant['ID'] == $value) {
93
                    $selected = true;
94
                }
95
96
                if ($multiple && in_array($variant['ID'], $value)) {
97
                    $selected = true;
98
                } elseif ($variant['ID'] === $value) {
99
                    $selected = true;
100
                }
101
102
                $comboBox .= "<option value='" . static::prepareToTagAttr($variant['ID']) . "' " . ($selected ? "selected" : "") . ">"
103
                    . static::prepareToTagAttr($variant['TITLE']) . "</option>";
104
            }
105
106
            $comboBox .= '</select>';
107
        }
108
109
        return $comboBox;
110
    }
111
112
    /**
113
     * @inheritdoc
114
     */
115
    protected function getValueReadonly()
116
    {
117
        $variants = $this->getVariants();
118
        $value = $variants[$this->getValue()]['TITLE'];
119
120
        return static::prepareToOutput($value);
121
    }
122
123
    /**
124
     * @inheritdoc
125
     */
126
    protected function getMultipleValueReadonly()
127
    {
128
        $variants = $this->getVariants();
129
        $values = $this->getMultipleValue();
130
        $result = '';
131
132
        if (empty($variants)) {
133
            $result = Loc::getMessage('DIGITALWAND_AH_MISSING_VARIANTS');
134
        } else {
135
            foreach ($variants as $id => $data) {
136
                $name = strlen($data["TITLE"]) > 0 ? $data["TITLE"] : "";
137
138
                if (in_array($id, $values)) {
139
                    $result .= static::prepareToOutput($name) . '<br/>';
140
                }
141
            }
142
        }
143
144
        return $result;
145
    }
146
147
    /**
148
     * Возвращает массив в следующем формате:
149
     * <code>
150
     * array(
151
     *      '123' => array('ID' => 123, 'TITLE' => 'ololo'),
152
     *      '456' => array('ID' => 456, 'TITLE' => 'blablabla'),
153
     *      '789' => array('ID' => 789, 'TITLE' => 'pish-pish'),
154
     * )
155
     * </code>
156
     * 
157
     * Результат будет выводиться в комбобоксе.
158
     * @return array
159
     */
160
    protected function getVariants()
161
    {
162
        $variants = $this->getSettings('VARIANTS');
163
164
        if (is_callable($variants)) {
165
            $var = $variants();
166
167
            if (is_array($var)) {
168
                return $this->formatVariants($var);
169
            }
170
        }elseif (is_array($variants) AND !empty($variants)) {
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...
171
            return $this->formatVariants($variants);
172
        }
173
174
        return array();
175
    }
176
177
    /**
178
     * Приводит варианты к нужному формату, если они заданы в виде одномерного массива.
179
     *
180
     * @param $variants
181
     *
182
     * @return array
183
     */
184
    protected function formatVariants($variants)
185
    {
186
        $formatted = array();
187
188
        foreach ($variants as $id => $data) {
189
            if (!is_array($data)) {
190
                $formatted[$id] = array(
191
                    'ID' => $id,
192
                    'TITLE' => $data
193
                );
194
            }
195
        }
196
197
        return $formatted;
198
    }
199
200
    /**
201
     * @inheritdoc
202
     */
203
    public function generateRow(&$row, $data)
204
    {
205
        if ($this->settings['EDIT_IN_LIST'] AND !$this->settings['READONLY']) {
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...
206
            $row->AddInputField($this->getCode(), array('style' => 'width:90%'));
207
        } else {
208
            $row->AddViewField($this->getCode(), $this->getValueReadonly());
209
        }
210
    }
211
212
    /**
213
     * @inheritdoc
214
     */
215
    public function showFilterHtml()
216
    {
217
        print '<tr>';
218
        print '<td>' . $this->getSettings('TITLE') . '</td>';
219
        print '<td>' . $this->getComboBox(false, true) . '</td>';
220
        print '</tr>';
221
    }
222
223
    /**
224
     * @inheritdoc
225
     */
226
    public function processEditAction()
227
    {
228
        if ($this->getSettings('MULTIPLE')) {
229
            $sphere = $this->data[$this->getCode()];
230
            unset($this->data[$this->getCode()]);
231
232
            foreach ($sphere as $sphereKey) {
233
                $this->data[$this->getCode()][] = array('VALUE' => $sphereKey);
234
            }
235
        }
236
237
        parent::processEditAction();
238
    }
239
}
240