Test Failed
Branch master (7b1793)
by Tymoteusz
15:35
created

InputDateTimeElement   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 244
Duplicated Lines 32.79 %

Importance

Changes 0
Metric Value
dl 80
loc 244
rs 10
c 0
b 0
f 0
wmc 26

2 Methods

Rating   Name   Duplication   Size   Complexity  
F render() 80 205 25
A getLanguageService() 0 3 1

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\Imaging\Icon;
18
use TYPO3\CMS\Core\Localization\LanguageService;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use TYPO3\CMS\Core\Utility\MathUtility;
21
use TYPO3\CMS\Core\Utility\StringUtility;
22
23
/**
24
 * Generation of TCEform elements of the type "input type=text"
25
 */
26
class InputDateTimeElement extends AbstractFormElement
27
{
28
    /**
29
     * Default field wizards enabled for this element.
30
     *
31
     * @var array
32
     */
33
    protected $defaultFieldWizard = [
34
        'localizationStateSelector' => [
35
            'renderType' => 'localizationStateSelector',
36
        ],
37
        'otherLanguageContent' => [
38
            'renderType' => 'otherLanguageContent',
39
            'after' => [
40
                'localizationStateSelector'
41
            ],
42
        ],
43
        'defaultLanguageDifferences' => [
44
            'renderType' => 'defaultLanguageDifferences',
45
            'after' => [
46
                'otherLanguageContent',
47
            ],
48
        ],
49
    ];
50
51
    /**
52
     * This will render a single-line input form field, possibly with various control/validation features
53
     *
54
     * @return array As defined in initializeResultArray() of AbstractNode
55
     * @throws \RuntimeException with invalid configuration
56
     */
57
    public function render()
58
    {
59
        $languageService = $this->getLanguageService();
60
61
        $table = $this->data['tableName'];
62
        $fieldName = $this->data['fieldName'];
63
        $row = $this->data['databaseRow'];
64
        $parameterArray = $this->data['parameterArray'];
65
        $resultArray = $this->initializeResultArray();
66
        $config = $parameterArray['fieldConf']['config'];
67
68
        $itemValue = $parameterArray['itemFormElValue'];
69
        $defaultInputWidth = 10;
70
        $evalList = GeneralUtility::trimExplode(',', $config['eval'], true);
71
        $nullControlNameEscaped = htmlspecialchars('control[active][' . $table . '][' . $row['uid'] . '][' . $fieldName . ']');
72
73
        if (in_array('date', $evalList, true)) {
74
            $format = 'date';
75
            $defaultInputWidth = 13;
76
        } elseif (in_array('datetime', $evalList, true)) {
77
            $format = 'datetime';
78
            $defaultInputWidth = 13;
79
        } elseif (in_array('time', $evalList, true)) {
80
            $format = 'time';
81
        } elseif (in_array('timesec', $evalList, true)) {
82
            $format = 'timesec';
83 View Code Duplication
        } else {
84
            throw new \RuntimeException(
85
                'Field "' . $fieldName . '" in table "' . $table . '" with renderType "inputDataTime" needs'
86
                . '"eval" set to either "date", "datetime", "time" or "timesec"',
87
                1483823746
88
            );
89
        }
90
91
        $size = MathUtility::forceIntegerInRange($config['size'] ?? $defaultInputWidth, $this->minimumInputWidth, $this->maxInputWidth);
92
        $width = (int)$this->formMaxWidth($size);
93
94 View Code Duplication
        if (isset($config['readOnly']) && $config['readOnly']) {
95
            // Early return for read only fields
96
            $itemValue = $this->formatValue($format, $itemValue);
97
            $html = [];
98
            $html[] = '<div class="formengine-field-item t3js-formengine-field-item">';
99
            $html[] =   '<div class="form-wizards-wrap">';
100
            $html[] =       '<div class="form-wizards-element">';
101
            $html[] =           '<div class="form-control-wrap" style="max-width: ' . $width . 'px">';
102
            $html[] =               '<input class="form-control" value="' . htmlspecialchars($itemValue) . '" type="text" disabled>';
103
            $html[] =           '</div>';
104
            $html[] =       '</div>';
105
            $html[] =   '</div>';
106
            $html[] = '</div>';
107
            $resultArray['html'] = implode(LF, $html);
108
            return $resultArray;
109
        }
110
111
        $attributes = [
112
            'value' => '',
113
            'id' => StringUtility::getUniqueId('formengine-input-'),
114
            'class' => implode(' ', [
115
                't3js-datetimepicker',
116
                'form-control',
117
                't3js-clearable',
118
                'hasDefaultValue',
119
            ]),
120
            'data-date-type' => $format,
121
            'data-formengine-validation-rules' => $this->getValidationDataAsJsonString($config),
122
            'data-formengine-input-params' => json_encode([
123
                'field' => $parameterArray['itemFormElName'],
124
                'evalList' => implode(',', $evalList)
125
            ]),
126
            'data-formengine-input-name' => $parameterArray['itemFormElName'],
127
        ];
128
129
        $maxLength = $config['max'] ?? 0;
130
        if ((int)$maxLength > 0) {
131
            $attributes['maxlength'] = (int)$maxLength;
132
        }
133
        if (!empty($config['placeholder'])) {
134
            $attributes['placeholder'] = trim($config['placeholder']);
135
        }
136
137
        if ($format === 'datetime' || $format === 'date') {
138
            // This only handles integer timestamps; if the field is a SQL native date(time), it was already converted
139
            // to an ISO-8601 date by the DatabaseRowDateTimeFields class. (those dates are stored as server local time)
140
            if (MathUtility::canBeInterpretedAsInteger($itemValue) && $itemValue != 0) {
141
                // We store UTC timestamps in the database.
142
                // Convert the timestamp to a proper ISO-8601 date so we get rid of timezone issues on the client.
143
                // Details: As the JS side is not capable of handling dates in the server's timezone
144
                // (moment.js can only handle UTC or browser's local timezone), we need to offset the value
145
                // to eliminate the timezone. JS will receive all dates as if they were UTC, which we undo on save in DataHandler
146
                $adjustedValue = $itemValue + date('Z', (int)$itemValue);
147
                // output date as a ISO-8601 date
148
                $itemValue = gmdate('c', $adjustedValue);
149
            }
150
            if (isset($config['range']['lower'])) {
151
                $attributes['data-date-minDate'] = (int)$config['range']['lower'];
152
            }
153
            if (isset($config['range']['upper'])) {
154
                $attributes['data-date-maxDate'] = (int)$config['range']['upper'];
155
            }
156
        }
157
        if (($format === 'time' || $format === 'timesec') && MathUtility::canBeInterpretedAsInteger($itemValue) && $itemValue != 0) {
158
            // time(sec) is stored as elapsed seconds in DB, hence we interpret it as UTC time on 1970-01-01
159
            // and pass on the ISO format to JS.
160
            $itemValue = gmdate('c', (int)$itemValue);
161
        }
162
163
        $fieldInformationResult = $this->renderFieldInformation();
164
        $fieldInformationHtml = $fieldInformationResult['html'];
165
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
166
167
        $fieldWizardResult = $this->renderFieldWizard();
168
        $fieldWizardHtml = $fieldWizardResult['html'];
169
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
170
171
        $fieldControlResult = $this->renderFieldControl();
172
        $fieldControlHtml = $fieldControlResult['html'];
173
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
174
175
        $expansionHtml = [];
176
        $expansionHtml[] = '<div class="form-control-wrap" style="max-width: ' . $width . 'px">';
177
        $expansionHtml[] =  '<div class="form-wizards-wrap">';
178
        $expansionHtml[] =      '<div class="form-wizards-element">';
179
        $expansionHtml[] =          '<div class="input-group">';
180
        $expansionHtml[] =              '<input type="text"' . GeneralUtility::implodeAttributes($attributes, true) . ' />';
181
        $expansionHtml[] =              '<input type="hidden" name="' . $parameterArray['itemFormElName'] . '" value="' . htmlspecialchars($itemValue) . '" />';
0 ignored issues
show
Bug introduced by
It seems like $itemValue can also be of type false; however, parameter $string of htmlspecialchars() does only seem to accept string, 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

181
        $expansionHtml[] =              '<input type="hidden" name="' . $parameterArray['itemFormElName'] . '" value="' . htmlspecialchars(/** @scrutinizer ignore-type */ $itemValue) . '" />';
Loading history...
182
        $expansionHtml[] =              '<span class="input-group-btn">';
183
        $expansionHtml[] =                  '<label class="btn btn-default" for="' . $attributes['id'] . '">';
184
        $expansionHtml[] =                      $this->iconFactory->getIcon('actions-edit-pick-date', Icon::SIZE_SMALL)->render();
185
        $expansionHtml[] =                  '</label>';
186
        $expansionHtml[] =              '</span>';
187
        $expansionHtml[] =          '</div>';
188
        $expansionHtml[] =      '</div>';
189
        $expansionHtml[] =      '<div class="form-wizards-items-aside">';
190
        $expansionHtml[] =          '<div class="btn-group">';
191
        $expansionHtml[] =              $fieldControlHtml;
192
        $expansionHtml[] =          '</div>';
193
        $expansionHtml[] =      '</div>';
194
        $expansionHtml[] =      '<div class="form-wizards-items-bottom">';
195
        $expansionHtml[] =          $fieldWizardHtml;
196
        $expansionHtml[] =      '</div>';
197
        $expansionHtml[] =  '</div>';
198
        $expansionHtml[] = '</div>';
199
        $expansionHtml = implode(LF, $expansionHtml);
200
201
        $fullElement = $expansionHtml;
202 View Code Duplication
        if ($this->hasNullCheckboxButNoPlaceholder()) {
203
            $checked = $itemValue !== null ? ' checked="checked"' : '';
204
            $fullElement = [];
205
            $fullElement[] = '<div class="t3-form-field-disable"></div>';
206
            $fullElement[] = '<div class="checkbox t3-form-field-eval-null-checkbox">';
207
            $fullElement[] =     '<label for="' . $nullControlNameEscaped . '">';
208
            $fullElement[] =         '<input type="hidden" name="' . $nullControlNameEscaped . '" value="0" />';
209
            $fullElement[] =         '<input type="checkbox" name="' . $nullControlNameEscaped . '" id="' . $nullControlNameEscaped . '" value="1"' . $checked . ' />';
210
            $fullElement[] =         $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.nullCheckbox');
211
            $fullElement[] =     '</label>';
212
            $fullElement[] = '</div>';
213
            $fullElement[] = $expansionHtml;
214
            $fullElement = implode(LF, $fullElement);
215
        } elseif ($this->hasNullCheckboxWithPlaceholder()) {
216
            $checked = $itemValue !== null ? ' checked="checked"' : '';
217
            $placeholder = $shortenedPlaceholder = $config['placeholder'] ?? '';
218
            $disabled = '';
219
            $fallbackValue = 0;
220
            if (strlen($placeholder) > 0) {
221
                $shortenedPlaceholder = GeneralUtility::fixed_lgd_cs($placeholder, 20);
222
                if ($placeholder !== $shortenedPlaceholder) {
223
                    $overrideLabel = sprintf(
224
                        $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
225
                        '<span title="' . htmlspecialchars($placeholder) . '">' . htmlspecialchars($shortenedPlaceholder) . '</span>'
226
                    );
227
                } else {
228
                    $overrideLabel = sprintf(
229
                        $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'),
230
                        htmlspecialchars($placeholder)
231
                    );
232
                }
233
            } else {
234
                $fallbackValue = 1;
235
                $checked = ' checked="checked"';
236
                $disabled = ' disabled="disabled"';
237
                $overrideLabel = $languageService->sL(
238
                    'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override_not_available'
239
                );
240
            }
241
            $fullElement = [];
242
            $fullElement[] = '<div class="checkbox t3js-form-field-eval-null-placeholder-checkbox">';
243
            $fullElement[] =     '<label for="' . $nullControlNameEscaped . '">';
244
            $fullElement[] =         '<input type="hidden" name="' . $nullControlNameEscaped . '" value="' . $fallbackValue . '" />';
245
            $fullElement[] =         '<input type="checkbox" name="' . $nullControlNameEscaped . '" id="' . $nullControlNameEscaped . '" value="1"' . $checked . $disabled . ' />';
246
            $fullElement[] =         $overrideLabel;
247
            $fullElement[] =     '</label>';
248
            $fullElement[] = '</div>';
249
            $fullElement[] = '<div class="t3js-formengine-placeholder-placeholder">';
250
            $fullElement[] =    '<div class="form-control-wrap" style="max-width:' . $width . 'px">';
251
            $fullElement[] =        '<input type="text" class="form-control" disabled="disabled" value="' . $shortenedPlaceholder . '" />';
252
            $fullElement[] =    '</div>';
253
            $fullElement[] = '</div>';
254
            $fullElement[] = '<div class="t3js-formengine-placeholder-formfield">';
255
            $fullElement[] =    $expansionHtml;
256
            $fullElement[] = '</div>';
257
            $fullElement = implode(LF, $fullElement);
258
        }
259
260
        $resultArray['html'] = '<div class="formengine-field-item t3js-formengine-field-item">' . $fieldInformationHtml . $fullElement . '</div>';
261
        return $resultArray;
262
    }
263
264
    /**
265
     * @return LanguageService
266
     */
267
    protected function getLanguageService(): LanguageService
268
    {
269
        return $GLOBALS['LANG'];
270
    }
271
}
272