Test Failed
Branch master (7b1793)
by Tymoteusz
36:50 queued 18:38
created

InputTextElement   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 276
Duplicated Lines 44.2 %

Importance

Changes 0
Metric Value
dl 122
loc 276
rs 10
c 0
b 0
f 0
wmc 29

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getLanguageService() 0 3 1
F render() 122 238 28

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace TYPO3\CMS\Backend\Form\Element;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use TYPO3\CMS\Core\Localization\LanguageService;
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
use TYPO3\CMS\Core\Utility\MathUtility;
20
use TYPO3\CMS\Core\Utility\StringUtility;
21
22
/**
23
 * General type=input element.
24
 *
25
 * This one kicks in if no specific renderType like "inputDateTime"
26
 * or "inputColorPicker" is set.
27
 */
28
class InputTextElement extends AbstractFormElement
29
{
30
    /**
31
     * Default field wizards enabled for this element.
32
     *
33
     * @var array
34
     */
35
    protected $defaultFieldWizard = [
36
        'localizationStateSelector' => [
37
            'renderType' => 'localizationStateSelector',
38
        ],
39
        'otherLanguageContent' => [
40
            'renderType' => 'otherLanguageContent',
41
            'after' => [
42
                'localizationStateSelector'
43
            ],
44
        ],
45
        'defaultLanguageDifferences' => [
46
            'renderType' => 'defaultLanguageDifferences',
47
            'after' => [
48
                'otherLanguageContent',
49
            ],
50
        ],
51
    ];
52
53
    /**
54
     * This will render a single-line input form field, possibly with various control/validation features
55
     *
56
     * @return array As defined in initializeResultArray() of AbstractNode
57
     */
58
    public function render()
59
    {
60
        $languageService = $this->getLanguageService();
61
62
        $table = $this->data['tableName'];
63
        $fieldName = $this->data['fieldName'];
64
        $row = $this->data['databaseRow'];
65
        $parameterArray = $this->data['parameterArray'];
66
        $resultArray = $this->initializeResultArray();
67
68
        $itemValue = $parameterArray['itemFormElValue'];
69
        $config = $parameterArray['fieldConf']['config'];
70
        $evalList = GeneralUtility::trimExplode(',', $config['eval'], true);
71
        $size = MathUtility::forceIntegerInRange($config['size'] ?? $this->defaultInputWidth, $this->minimumInputWidth, $this->maxInputWidth);
72
        $width = (int)$this->formMaxWidth($size);
73
        $nullControlNameEscaped = htmlspecialchars('control[active][' . $table . '][' . $row['uid'] . '][' . $fieldName . ']');
74
75 View Code Duplication
        if ($config['readOnly']) {
76
            // Early return for read only fields
77
            if (in_array('password', $evalList, true)) {
78
                $itemValue = $itemValue ? '*********' : '';
79
            }
80
            $html = [];
81
            $html[] = '<div class="formengine-field-item t3js-formengine-field-item">';
82
            $html[] =   '<div class="form-wizards-wrap">';
83
            $html[] =       '<div class="form-wizards-element">';
84
            $html[] =           '<div class="form-control-wrap" style="max-width: ' . $width . 'px">';
85
            $html[] =               '<input class="form-control" value="' . htmlspecialchars($itemValue) . '" type="text" disabled>';
86
            $html[] =           '</div>';
87
            $html[] =       '</div>';
88
            $html[] =   '</div>';
89
            $html[] = '</div>';
90
            $resultArray['html'] = implode(LF, $html);
91
            return $resultArray;
92
        }
93
94
        // @todo: The whole eval handling is a mess and needs refactoring
95 View Code Duplication
        foreach ($evalList as $func) {
96
            // @todo: This is ugly: The code should find out on it's own whether a eval definition is a
97
            // @todo: keyword like "date", or a class reference. The global registration could be dropped then
98
            // Pair hook to the one in \TYPO3\CMS\Core\DataHandling\DataHandler::checkValue_input_Eval()
99
            if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
100
                if (class_exists($func)) {
101
                    $evalObj = GeneralUtility::makeInstance($func);
102
                    if (method_exists($evalObj, 'deevaluateFieldValue')) {
103
                        $_params = [
104
                            'value' => $itemValue
105
                        ];
106
                        $itemValue = $evalObj->deevaluateFieldValue($_params);
107
                    }
108
                    if (method_exists($evalObj, 'returnFieldJS')) {
109
                        $resultArray['additionalJavaScriptPost'][] = 'TBE_EDITOR.customEvalFunctions[' . GeneralUtility::quoteJSvalue($func) . ']'
110
                            . ' = function(value) {' . $evalObj->returnFieldJS() . '};';
111
                    }
112
                }
113
            }
114
        }
115
116
        $attributes = [
117
            'value' => '',
118
            'id' => StringUtility::getUniqueId('formengine-input-'),
119
            'class' => implode(' ', [
120
                'form-control',
121
                't3js-clearable',
122
                'hasDefaultValue',
123
            ]),
124
            'data-formengine-validation-rules' => $this->getValidationDataAsJsonString($config),
125
            'data-formengine-input-params' => json_encode([
126
                'field' => $parameterArray['itemFormElName'],
127
                'evalList' => implode(',', $evalList),
128
                'is_in' => trim($config['is_in'])
129
            ]),
130
            'data-formengine-input-name' => $parameterArray['itemFormElName'],
131
        ];
132
133
        $maxLength = $config['max'] ?? 0;
134
        if ((int)$maxLength > 0) {
135
            $attributes['maxlength'] = (int)$maxLength;
136
        }
137
        if (!empty($config['placeholder'])) {
138
            $attributes['placeholder'] = trim($config['placeholder']);
139
        }
140 View Code Duplication
        if (isset($config['autocomplete'])) {
141
            $attributes['autocomplete'] = empty($config['autocomplete']) ? 'new-' . $fieldName : 'on';
142
        }
143
144
        $valuePickerHtml = [];
145 View Code Duplication
        if (isset($config['valuePicker']['items']) && is_array($config['valuePicker']['items'])) {
146
            $mode = $config['valuePicker']['mode'] ?? '';
147
            $itemName = $parameterArray['itemFormElName'];
148
            $fieldChangeFunc = $parameterArray['fieldChangeFunc'];
149
            if ($mode === 'append') {
150
                $assignValue = 'document.querySelectorAll(' . GeneralUtility::quoteJSvalue('[data-formengine-input-name="' . $itemName . '"]') . ')[0]'
151
                    . '.value+=\'\'+this.options[this.selectedIndex].value';
152
            } elseif ($mode === 'prepend') {
153
                $assignValue = 'document.querySelectorAll(' . GeneralUtility::quoteJSvalue('[data-formengine-input-name="' . $itemName . '"]') . ')[0]'
154
                    . '.value=\'\'+this.options[this.selectedIndex].value+document.editform[' . GeneralUtility::quoteJSvalue($itemName) . '].value';
155
            } else {
156
                $assignValue = 'document.querySelectorAll(' . GeneralUtility::quoteJSvalue('[data-formengine-input-name="' . $itemName . '"]') . ')[0]'
157
                    . '.value=this.options[this.selectedIndex].value';
158
            }
159
            $valuePickerHtml[] = '<select';
160
            $valuePickerHtml[] =  ' class="form-control tceforms-select tceforms-wizardselect"';
161
            $valuePickerHtml[] =  ' onchange="' . htmlspecialchars($assignValue . ';this.blur();this.selectedIndex=0;' . implode('', $fieldChangeFunc)) . '"';
162
            $valuePickerHtml[] = '>';
163
            $valuePickerHtml[] = '<option></option>';
164
            foreach ($config['valuePicker']['items'] as $item) {
165
                $valuePickerHtml[] = '<option value="' . htmlspecialchars($item[1]) . '">' . htmlspecialchars($languageService->sL($item[0])) . '</option>';
166
            }
167
            $valuePickerHtml[] = '</select>';
168
        }
169
170
        $valueSliderHtml = [];
171
        if (isset($config['slider']) && is_array($config['slider'])) {
172
            $resultArray['requireJsModules'][] = 'TYPO3/CMS/Backend/ValueSlider';
173
            $min = $config['range']['lower'] ?? 0;
174
            $max = $config['range']['upper'] ?? 10000;
175
            $step = $config['slider']['step'] ?? 1;
176
            $width = $config['slider']['width'] ?? 400;
177
            $valueType = 'null';
178
            if (in_array('int', $evalList, true)) {
179
                $valueType = 'int';
180
                $itemValue = (int)$itemValue;
181
            } elseif (in_array('double2', $evalList, true)) {
182
                $valueType = 'double';
183
                $itemValue = (double)$itemValue;
184
            }
185
            $callbackParams = [ $table, $row['uid'], $fieldName, $parameterArray['itemFormElName'] ];
186
            $id = 'slider-' . md5($parameterArray['itemFormElName']);
187
            $valueSliderHtml[] = '<div';
188
            $valueSliderHtml[] =    ' id="' . $id . '"';
189
            $valueSliderHtml[] =    ' data-slider-id="' . $id . '"';
190
            $valueSliderHtml[] =    ' data-slider-min="' . (int)$min . '"';
191
            $valueSliderHtml[] =    ' data-slider-max="' . (int)$max . '"';
192
            $valueSliderHtml[] =    ' data-slider-step="' . htmlspecialchars($step) . '"';
193
            $valueSliderHtml[] =    ' data-slider-value="' . htmlspecialchars($itemValue) . '"';
194
            $valueSliderHtml[] =    ' data-slider-value-type="' . htmlspecialchars($valueType) . '"';
195
            $valueSliderHtml[] =    ' data-slider-item-name="' . htmlspecialchars($parameterArray['itemFormElName']) . '"';
196
            $valueSliderHtml[] =    ' data-slider-callback-params="' . htmlspecialchars(json_encode($callbackParams)) . '"';
197
            $valueSliderHtml[] =    ' style="width: ' . $width . 'px;"';
198
            $valueSliderHtml[] = '>';
199
            $valueSliderHtml[] = '</div>';
200
        }
201
202
        $fieldInformationResult = $this->renderFieldInformation();
203
        $fieldInformationHtml = $fieldInformationResult['html'];
204
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
205
206
        $fieldControlResult = $this->renderFieldControl();
207
        $fieldControlHtml = $fieldControlResult['html'];
208
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
209
210
        $fieldWizardResult = $this->renderFieldWizard();
211
        $fieldWizardHtml = $fieldWizardResult['html'];
212
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
213
214
        $mainFieldHtml = [];
215
        $mainFieldHtml[] = '<div class="form-control-wrap" style="max-width: ' . $width . 'px">';
216
        $mainFieldHtml[] =  '<div class="form-wizards-wrap">';
217
        $mainFieldHtml[] =      '<div class="form-wizards-element">';
218
        $mainFieldHtml[] =          '<input type="text"' . GeneralUtility::implodeAttributes($attributes, true) . ' />';
219
        $mainFieldHtml[] =          '<input type="hidden" name="' . $parameterArray['itemFormElName'] . '" value="' . htmlspecialchars($itemValue) . '" />';
220
        $mainFieldHtml[] =      '</div>';
221
        $mainFieldHtml[] =      '<div class="form-wizards-items-aside">';
222
        $mainFieldHtml[] =          '<div class="btn-group">';
223
        $mainFieldHtml[] =              implode(LF, $valuePickerHtml);
224
        $mainFieldHtml[] =              implode(LF, $valueSliderHtml);
225
        $mainFieldHtml[] =              $fieldControlHtml;
226
        $mainFieldHtml[] =          '</div>';
227
        $mainFieldHtml[] =      '</div>';
228
        $mainFieldHtml[] =      '<div class="form-wizards-items-bottom">';
229
        $mainFieldHtml[] =          $fieldWizardHtml;
230
        $mainFieldHtml[] =      '</div>';
231
        $mainFieldHtml[] =  '</div>';
232
        $mainFieldHtml[] = '</div>';
233
        $mainFieldHtml = implode(LF, $mainFieldHtml);
234
235
        $fullElement = $mainFieldHtml;
236 View Code Duplication
        if ($this->hasNullCheckboxButNoPlaceholder()) {
237
            $checked = $itemValue !== null ? ' checked="checked"' : '';
238
            $fullElement = [];
239
            $fullElement[] = '<div class="t3-form-field-disable"></div>';
240
            $fullElement[] = '<div class="checkbox t3-form-field-eval-null-checkbox">';
241
            $fullElement[] =     '<label for="' . $nullControlNameEscaped . '">';
242
            $fullElement[] =         '<input type="hidden" name="' . $nullControlNameEscaped . '" value="0" />';
243
            $fullElement[] =         '<input type="checkbox" name="' . $nullControlNameEscaped . '" id="' . $nullControlNameEscaped . '" value="1"' . $checked . ' />';
244
            $fullElement[] =         $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.nullCheckbox');
245
            $fullElement[] =     '</label>';
246
            $fullElement[] = '</div>';
247
            $fullElement[] = $mainFieldHtml;
248
            $fullElement = implode(LF, $fullElement);
249
        } elseif ($this->hasNullCheckboxWithPlaceholder()) {
250
            $checked = $itemValue !== null ? ' checked="checked"' : '';
251
            $placeholder = $shortenedPlaceholder = $config['placeholder'] ?? '';
252
            $disabled = '';
253
            $fallbackValue = 0;
254
            if (strlen($placeholder) > 0) {
255
                $shortenedPlaceholder = GeneralUtility::fixed_lgd_cs($placeholder, 20);
256
                if ($placeholder !== $shortenedPlaceholder) {
257
                    $overrideLabel = sprintf(
258
                        $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
259
                        '<span title="' . htmlspecialchars($placeholder) . '">' . htmlspecialchars($shortenedPlaceholder) . '</span>'
260
                    );
261
                } else {
262
                    $overrideLabel = sprintf(
263
                        $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
264
                        htmlspecialchars($placeholder)
265
                    );
266
                }
267
            } else {
268
                $fallbackValue = 1;
269
                $checked = ' checked="checked"';
270
                $disabled = ' disabled="disabled"';
271
                $overrideLabel = $languageService->sL(
272
                    'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override_not_available'
273
                );
274
            }
275
            $fullElement = [];
276
            $fullElement[] = '<div class="checkbox t3js-form-field-eval-null-placeholder-checkbox">';
277
            $fullElement[] =     '<label for="' . $nullControlNameEscaped . '">';
278
            $fullElement[] =         '<input type="hidden" name="' . $nullControlNameEscaped . '" value="' . $fallbackValue . '" />';
279
            $fullElement[] =         '<input type="checkbox" name="' . $nullControlNameEscaped . '" id="' . $nullControlNameEscaped . '" value="1"' . $checked . $disabled . ' />';
280
            $fullElement[] =         $overrideLabel;
281
            $fullElement[] =     '</label>';
282
            $fullElement[] = '</div>';
283
            $fullElement[] = '<div class="t3js-formengine-placeholder-placeholder">';
284
            $fullElement[] =    '<div class="form-control-wrap" style="max-width:' . $width . 'px">';
285
            $fullElement[] =        '<input type="text" class="form-control" disabled="disabled" value="' . $shortenedPlaceholder . '" />';
286
            $fullElement[] =    '</div>';
287
            $fullElement[] = '</div>';
288
            $fullElement[] = '<div class="t3js-formengine-placeholder-formfield">';
289
            $fullElement[] =    $mainFieldHtml;
290
            $fullElement[] = '</div>';
291
            $fullElement = implode(LF, $fullElement);
292
        }
293
294
        $resultArray['html'] = '<div class="formengine-field-item t3js-formengine-field-item">' . $fieldInformationHtml . $fullElement . '</div>';
295
        return $resultArray;
296
    }
297
298
    /**
299
     * @return LanguageService
300
     */
301
    protected function getLanguageService()
302
    {
303
        return $GLOBALS['LANG'];
304
    }
305
}
306