Passed
Pull Request — master (#123)
by
unknown
11:14
created

validateAdditionalFields()   F

Complexity

Conditions 25
Paths 432

Size

Total Lines 81
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 25
eloc 57
nc 432
nop 2
dl 0
loc 81
rs 0.7887
c 1
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
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
namespace Kitodo\Dlf\Task;
13
14
use Kitodo\Dlf\Common\Helper;
15
use TYPO3\CMS\Backend\Tree\Repository\PageTreeRepository;
16
use TYPO3\CMS\Core\Database\Connection;
17
use TYPO3\CMS\Core\Database\ConnectionPool;
18
use TYPO3\CMS\Core\Messaging\FlashMessage;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use TYPO3\CMS\Scheduler\AdditionalFieldProviderInterface;
21
use TYPO3\CMS\Scheduler\Controller\SchedulerModuleController;
22
use TYPO3\CMS\Scheduler\Task\AbstractTask;
23
24
/**
25
 * Base class for additional fields classes of scheduler tasks.
26
 *
27
 * @package TYPO3
28
 * @subpackage dlf
29
 *
30
 * @access public
31
 */
32
class BaseAdditionalFieldProvider implements AdditionalFieldProviderInterface
33
{
34
    /**
35
     * Gets additional fields to render in the form to add/edit a task
36
     *
37
     * @param array $taskInfo Values of the fields from the add/edit task form
38
     * @param \TYPO3\CMS\Scheduler\Task\AbstractTask $task The task object being edited. Null when adding a task!
39
     * @param \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $schedulerModule Reference to the scheduler backend module
40
     * @return array A two dimensional array, array('Identifier' => array('fieldId' => array('code' => '', 'label' => '', 'cshKey' => '', 'cshLabel' => ''))
41
     */
42
    public function getAdditionalFields(array &$taskInfo, $task, SchedulerModuleController $schedulerModule)
43
    {
44
        return [];
45
    }
46
47
    /**
48
     * Validates the additional fields' values
49
     *
50
     * @param array $submittedData An array containing the data submitted by the add/edit task form
51
     * @param \TYPO3\CMS\Scheduler\Controller\SchedulerModuleController $schedulerModule Reference to the scheduler backend module
52
     * @return bool TRUE if validation was ok (or selected class is not relevant), FALSE otherwise
53
     */
54
    public function validateAdditionalFields(array &$submittedData, SchedulerModuleController $schedulerModule)
55
    {
56
        $fieldsValid = true;
57
58
        Helper::getLanguageService()->includeLLFile('EXT:dlf/Resources/Private/Language/locallang_tasks.xlf');
59
60
        $messageTitle = Helper::getLanguageService()->getLL('additionalFields.error');
61
        $messageSeverity = FlashMessage::ERROR;
62
63
        if (isset($submittedData['doc']) && empty($submittedData['doc'])) {
64
            Helper::addMessage(
65
                Helper::getLanguageService()->getLL('additionalFields.doc') . ' ' . Helper::getLanguageService()->getLL('additionalFields.valid'),
66
                $messageTitle,
67
                $messageSeverity,
68
                true,
69
                'core.template.flashMessages'
70
            );
71
            $fieldsValid = false;
72
        }
73
74
        if ((isset($submittedData['pid']) && (int) $submittedData['pid'] <= 0)) {
75
            Helper::addMessage(
76
                Helper::getLanguageService()->getLL('additionalFields.pid') . ' ' . Helper::getLanguageService()->getLL('additionalFields.valid'),
77
                $messageTitle,
78
                $messageSeverity,
79
                true,
80
                'core.template.flashMessages'
81
            );
82
            $fieldsValid = false;
83
        }
84
85
        if (!isset($submittedData['commit']) && !isset($submittedData['optimize']) && !isset($submittedData['pid']) && ($submittedData['class'] != 'Kitodo\Dlf\Task\SuggestBuildTask')) {
86
            Helper::addMessage(
87
                Helper::getLanguageService()->getLL('additionalFields.commitOrOptimize'),
88
                $messageTitle,
89
                $messageSeverity,
90
                true,
91
                'core.template.flashMessages'
92
            );
93
            $fieldsValid = false;
94
        }
95
96
        if (!$submittedData['uid']) {
97
            $messageTitle = Helper::getLanguageService()->getLL('additionalFields.warning');
98
            $messageSeverity = FlashMessage::WARNING;
99
        }
100
101
        if ((isset($submittedData['lib']) && (int) $submittedData['lib'] <= 0)) {
102
            Helper::addMessage(
103
                Helper::getLanguageService()->getLL('additionalFields.lib') . ' ' . Helper::getLanguageService()->getLL('additionalFields.valid'),
104
                $messageTitle,
105
                $messageSeverity,
106
                true,
107
                'core.template.flashMessages'
108
            );
109
            $fieldsValid = $messageSeverity === FlashMessage::ERROR ? false : $fieldsValid;
110
        }
111
112
        if ((isset($submittedData['solr']) && (int) $submittedData['solr'] <= 0) || !isset($submittedData['solr'])) {
113
            Helper::addMessage(
114
                Helper::getLanguageService()->getLL('additionalFields.solr') . ' ' . Helper::getLanguageService()->getLL('additionalFields.valid'),
115
                $messageTitle,
116
                $messageSeverity,
117
                true,
118
                'core.template.flashMessages'
119
            );
120
            $fieldsValid = $messageSeverity === FlashMessage::ERROR ? false : $fieldsValid;
121
        }
122
123
        if (((isset($submittedData['coll']) && isset($submittedData['all'])) || (!isset($submittedData['coll']) && !isset($submittedData['all'])))
124
            && !isset($submittedData['doc']) && !isset($submittedData['lib']) && isset($submittedData['pid'])) {
125
            Helper::addMessage(
126
                Helper::getLanguageService()->getLL('additionalFields.collOrAll'),
127
                $messageTitle,
128
                $messageSeverity,
129
                true,
130
                'core.template.flashMessages'
131
            );
132
            $fieldsValid = $messageSeverity === FlashMessage::ERROR ? false : $fieldsValid;
133
        }
134
        return $fieldsValid;
135
    }
136
137
    /**
138
     * Takes care of saving the additional fields' values in the task's object
139
     *
140
     * @param array $submittedData An array containing the data submitted by the add/edit task form
141
     * @param BaseTask $task Reference to the scheduler backend module
142
     * @return void
143
     */
144
    public function saveAdditionalFields(array $submittedData, AbstractTask $task)
145
    {
146
        /** @var BaseTask $task */
147
        $task->setDryRun(!empty($submittedData['dryRun']));
148
        if (isset($submittedData['doc'])) {
149
            $task->setDoc(htmlspecialchars($submittedData['doc']));
150
        }
151
        if (isset($submittedData['lib'])) {
152
            $task->setLib((int) $submittedData['lib']);
153
        }
154
        if (isset($submittedData['coll']) && is_array($submittedData['coll'])) {
155
            $task->setColl($submittedData['coll']);
156
        } else {
157
            $task->setColl([]);
158
        }
159
        if (isset($submittedData['pid'])) {
160
            $task->setPid((int) $submittedData['pid']);
161
        }
162
        if (isset($submittedData['solr'])) {
163
            $task->setSolr((int) $submittedData['solr']);
164
        }
165
        if (isset($submittedData['owner'])) {
166
            $task->setOwner(htmlspecialchars($submittedData['owner']));
167
        }
168
        $task->setAll(!empty($submittedData['all']));
169
        if (isset($submittedData['from'])) {
170
            $task->setFrom(htmlspecialchars($submittedData['from']));
171
        }
172
        if (isset($submittedData['until'])) {
173
            $task->setUntil(htmlspecialchars($submittedData['until']));
174
        }
175
        if (isset($submittedData['set'])) {
176
            $task->setSet(htmlspecialchars($submittedData['set']));
177
        }
178
        $task->setSoftCommit(!empty($submittedData['softCommit']));
179
        $task->setCommit(!empty($submittedData['commit']));
180
        $task->setOptimize(!empty($submittedData['optimize']));
181
    }
182
183
    /**
184
     * Return HTML for dry run checkbox
185
     *
186
     * @access protected
187
     *
188
     * @param bool $dryRun
189
     *
190
     * @return array additional field dry run checkbox
191
     */
192
    protected function getDryRunField(bool $dryRun): array
193
    {
194
        $fieldName = 'dryRun';
195
        $fieldId = 'task_' . $fieldName;
196
        $fieldHtml = '<input type="checkbox" name="tx_scheduler[' . $fieldName . ']" id="' . $fieldId . '" value="1"' . ($dryRun ? ' checked="checked"' : '') . '>';
197
        return [
198
            'code' => $fieldHtml,
199
            'label' => 'LLL:EXT:dlf/Resources/Private/Language/locallang_tasks.xlf:additionalFields.dryRun',
200
            'cshKey' => '_MOD_system_txschedulerM1',
201
            'cshLabel' => $fieldId
202
        ];
203
    }
204
205
    /**
206
     * Return HTML for solr dropdown
207
     *
208
     * @access protected
209
     *
210
     * @param int $solr UID of the selected Solr core
211
     * @param int|null $pid UID of the selected storage page
212
     *
213
     * @return array additional field solr dropdown
214
     */
215
    protected function getSolrField(int $solr, int $pid = null): array
216
    {
217
        $fieldName = 'solr';
218
        $fieldId = 'task_' . $fieldName;
219
220
        $allSolrCores = $this->getSolrCores($pid);
221
        $options = [];
222
        $options[] = '<option value="-1"></option>';
223
        foreach ($allSolrCores as $label => $uid) {
224
            $options[] = '<option value="' . $uid . '" ' . ($solr == $uid ? 'selected' : '') . ' >' . $label . '</option>';
225
        };
226
        $fieldHtml = '<select name="tx_scheduler[' . $fieldName . ']" id="' . $fieldId . '">' . implode("\n", $options) . '</select>';
227
        return [
228
            'code' => $fieldHtml,
229
            'label' => 'LLL:EXT:dlf/Resources/Private/Language/locallang_tasks.xlf:additionalFields.solr',
230
            'cshKey' => '_MOD_system_txschedulerM1',
231
            'cshLabel' => $fieldId
232
        ];
233
    }
234
235
    /**
236
     * Return html for page dropdown
237
     *
238
     * @access protected
239
     *
240
     * @param int $pid UID of the selected storage page
241
     *
242
     * @return array additional field storage page dropdown
243
     */
244
    protected function getPidField(int $pid): array
245
    {
246
        $fieldName = 'pid';
247
        $fieldId = 'task_' . $fieldName;
248
249
        $pageRepository = GeneralUtility::makeInstance(PageTreeRepository::class);
250
        $pages = $pageRepository->getTree(0);
251
252
        $options = [];
253
        foreach ($pages['_children'] as $page) {
254
            if ($page['doktype'] == 254) {
255
                $options[] = '<option value="' . $page['uid'] . '" ' . ($pid == $page['uid'] ? 'selected' : '') . ' >' . $page['title'] . '</option>';
256
            }
257
        }
258
259
        $fieldHtml = '<select name="tx_scheduler[' . $fieldName . ']" id="' . $fieldId . '">' . implode("\n", $options) . '</select>';
260
        return [
261
            'code' => $fieldHtml,
262
            'label' => 'LLL:EXT:dlf/Resources/Private/Language/locallang_tasks.xlf:additionalFields.pid',
263
            'cshKey' => '_MOD_system_txschedulerM1',
264
            'cshLabel' => $fieldId
265
        ];
266
    }
267
268
    /**
269
     * Return HTML for owner text field
270
     *
271
     * @access protected
272
     *
273
     * @param string $owner registered owner
274
     *
275
     * @return array additional field owner text field
276
     */
277
    protected function getOwnerField(string $owner): array
278
    {
279
        $fieldName = 'owner';
280
        $fieldId = 'task_' . $fieldName;
281
        $fieldHtml = '<input type="text" name="tx_scheduler[' . $fieldName . ']" id="' . $fieldId . '" value="' . $owner . '" >';
282
        return [
283
            'code' => $fieldHtml,
284
            'label' => 'LLL:EXT:dlf/Resources/Private/Language/locallang_tasks.xlf:additionalFields.owner',
285
            'cshKey' => '_MOD_system_txschedulerM1',
286
            'cshLabel' => $fieldId
287
        ];
288
    }
289
290
    /**
291
     * Fetches all Solr cores on given page.
292
     *
293
     * @access protected
294
     *
295
     * @param int|null $pid UID of storage page
296
     *
297
     * @return array Array of valid Solr cores
298
     */
299
    private function getSolrCores(int $pid = null): array
300
    {
301
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_dlf_solrcores');
302
303
        $solrCores = [];
304
        $result = $queryBuilder->select('uid', 'label', 'index_name')
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
305
            ->from('tx_dlf_solrcores');
306
        if ($pid !== null) {
307
            $queryBuilder->where(
308
                $queryBuilder->expr()
309
                    ->eq('pid', $queryBuilder->createNamedParameter((int) $pid, Connection::PARAM_INT))
310
            );
311
        }
312
        $result = $queryBuilder->execute();
313
314
        while ($record = $result->fetchAssociative()) {
315
            $solrCores[$record['label'] . ' (' . $record['index_name'] . ')'] = $record['uid'];
316
        }
317
318
        return $solrCores;
319
    }
320
321
    /**
322
     * Return HTML for soft commit checkbox
323
     *
324
     * @access protected
325
     *
326
     * @param bool $softCommit
327
     *
328
     * @return array additional field soft commit checkbox
329
     */
330
    protected function getSoftCommitField(bool $softCommit): array
331
    {
332
        $fieldName = 'softCommit';
333
        $fieldId = 'task_' . $fieldName;
334
        $fieldHtml = '<input type="checkbox" name="tx_scheduler[' . $fieldName . ']" id="' . $fieldId . '" value="1"' . ($softCommit ? ' checked="checked"' : '') . '>';
335
        return [
336
            'code' => $fieldHtml,
337
            'label' => 'LLL:EXT:dlf/Resources/Private/Language/locallang_tasks.xlf:additionalFields.softCommit',
338
            'cshKey' => '_MOD_system_txschedulerM1',
339
            'cshLabel' => $fieldId
340
        ];
341
    }
342
}
343