Completed
Push — master ( 0ecd6b...9f36b3 )
by Tim
03:56
created

CalendarController::listAction()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 31
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 25
nc 2
nop 8

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * Calendar.
4
 */
5
namespace HDNET\Calendarize\Controller;
6
7
use HDNET\Calendarize\Domain\Model\Index;
8
use HDNET\Calendarize\Register;
9
use HDNET\Calendarize\Utility\DateTimeUtility;
10
use HDNET\Calendarize\Utility\EventUtility;
11
use HDNET\Calendarize\Utility\ExtensionConfigurationUtility;
12
use HDNET\Calendarize\Utility\TranslateUtility;
13
use TYPO3\CMS\Backend\Utility\BackendUtility;
14
use TYPO3\CMS\Core\Utility\GeneralUtility;
15
use TYPO3\CMS\Core\Utility\MathUtility;
16
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
17
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
18
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
19
20
/**
21
 * Calendar.
22
 */
23
class CalendarController extends AbstractController
24
{
25
    /**
26
     * Init all actions.
27
     */
28
    public function initializeAction()
29
    {
30
        parent::initializeAction();
31
        $this->indexRepository->setIndexTypes(GeneralUtility::trimExplode(',', $this->settings['configuration'], true));
32
        $additionalSlotArguments = [
33
            'contentRecord' => $this->configurationManager->getContentObject()->data,
34
            'settings' => $this->settings,
35
        ];
36
        $this->indexRepository->setAdditionalSlotArguments($additionalSlotArguments);
37
38
        if (isset($this->settings['sorting'])) {
39
            $this->indexRepository->setDefaultSortingDirection($this->settings['sorting']);
40
        }
41
42
        if (isset($this->arguments['startDate'])) {
43
            $this->arguments['startDate']->getPropertyMappingConfiguration()
44
                ->setTypeConverterOption(
45
                    DateTimeConverter::class,
46
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
47
                    $this->settings['dateFormat']
48
                );
49
        }
50
        if (isset($this->arguments['endDate'])) {
51
            $this->arguments['endDate']->getPropertyMappingConfiguration()
52
                ->setTypeConverterOption(
53
                    DateTimeConverter::class,
54
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
55
                    $this->settings['dateFormat']
56
                );
57
        }
58
        if ($this->request->hasArgument('event') && $this->actionMethodName == 'detailAction') {
59
            // default configuration
60
            $configurationName = $this->settings['configuration'];
61
            // configuration overwritten by argument?
62
            if ($this->request->hasArgument('extensionConfiguration')) {
63
                $configurationName = $this->request->getArgument('extensionConfiguration');
64
            }
65
            // get the configuration
66
            $configuration = ExtensionConfigurationUtility::get($configurationName);
67
68
            // get Event by Configuration and Uid
69
            $event = EventUtility::getOriginalRecordByConfiguration($configuration, $this->request->getArgument('event'));
70
            $index = $this->indexRepository->findByEventTraversing($event, true, false, 1)->getFirst();
71
72
            // if there is a valid index in the event
73
            if ($index) {
74
                $this->redirect('detail', null, null, ['index' => $index]);
75
            }
76
        }
77
    }
78
79
    /**
80
     * Latest action.
81
     *
82
     * @param \HDNET\Calendarize\Domain\Model\Index $index
83
     * @param \DateTime                             $startDate
84
     * @param \DateTime                             $endDate
85
     * @param array                                 $customSearch *
86
     * @param int                                   $year
87
     * @param int                                   $month
88
     * @param int                                   $week
89
     *
90
     * @ignorevalidation $startDate
91
     * @ignorevalidation $endDate
92
     * @ignorevalidation $customSearch
93
     *
94
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
95
     */
96
    public function latestAction(
97
        Index $index = null,
98
        \DateTime $startDate = null,
99
        \DateTime $endDate = null,
100
        array $customSearch = [],
101
        $year = null,
102
        $month = null,
103
        $week = null
104
    ) {
105
        $this->checkStaticTemplateIsIncluded();
106
        if (($index instanceof Index) && in_array('detail', $this->getAllowedActions())) {
107
            $this->forward('detail');
108
        }
109
110
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
111
112
        $this->slotExtendedAssignMultiple([
113
            'indices' => $search['indices'],
114
            'searchMode' => $search['searchMode'],
115
            'searchParameter' => [
116
                'startDate' => $startDate,
117
                'endDate' => $endDate,
118
                'customSearch' => $customSearch,
119
                'year' => $year,
120
                'month' => $month,
121
                'week' => $week,
122
            ],
123
        ], __CLASS__, __FUNCTION__);
124
    }
125
126
    /**
127
     * Result action.
128
     *
129
     * @param \HDNET\Calendarize\Domain\Model\Index $index
130
     * @param \DateTime                             $startDate
131
     * @param \DateTime                             $endDate
132
     * @param array                                 $customSearch
133
     * @param int                                   $year
134
     * @param int                                   $month
135
     * @param int                                   $week
136
     *
137
     * @ignorevalidation $startDate
138
     * @ignorevalidation $endDate
139
     * @ignorevalidation $customSearch
140
     *
141
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
142
     */
143
    public function resultAction(
144
        Index $index = null,
145
        \DateTime $startDate = null,
146
        \DateTime $endDate = null,
147
        array $customSearch = [],
148
        $year = null,
149
        $month = null,
150
        $week = null
151
    ) {
152
        $this->checkStaticTemplateIsIncluded();
153
        if (($index instanceof Index) && in_array('detail', $this->getAllowedActions())) {
154
            $this->forward('detail');
155
        }
156
157
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
158
159
        $this->slotExtendedAssignMultiple([
160
            'indices' => $search['indices'],
161
            'searchMode' => $search['searchMode'],
162
            'searchParameter' => [
163
                'startDate' => $startDate,
164
                'endDate' => $endDate,
165
                'customSearch' => $customSearch,
166
                'year' => $year,
167
                'month' => $month,
168
                'week' => $week,
169
            ],
170
        ], __CLASS__, __FUNCTION__);
171
    }
172
173
    /**
174
     * List action.
175
     *
176
     * @param \HDNET\Calendarize\Domain\Model\Index $index
177
     * @param \DateTime                             $startDate
178
     * @param \DateTime                             $endDate
179
     * @param array                                 $customSearch *
180
     * @param int                                   $year
181
     * @param int                                   $month
182
     * @param int                                   $day
183
     * @param int                                   $week
184
     *
185
     * @ignorevalidation $startDate
186
     * @ignorevalidation $endDate
187
     * @ignorevalidation $customSearch
188
     *
189
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
190
     */
191
    public function listAction(
192
        Index $index = null,
193
        \DateTime $startDate = null,
194
        \DateTime $endDate = null,
195
        array $customSearch = [],
196
        $year = null,
197
        $month = null,
198
        $day = null,
199
        $week = null
200
    ) {
201
        $this->checkStaticTemplateIsIncluded();
202
        if (($index instanceof Index) && in_array('detail', $this->getAllowedActions())) {
203
            $this->forward('detail');
204
        }
205
206
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, $day, $week);
207
208
        $this->slotExtendedAssignMultiple([
209
            'indices' => $search['indices'],
210
            'searchMode' => $search['searchMode'],
211
            'searchParameter' => [
212
                'startDate' => $startDate,
213
                'endDate' => $endDate,
214
                'customSearch' => $customSearch,
215
                'year' => $year,
216
                'month' => $month,
217
                'day' => $day,
218
                'week' => $week,
219
            ],
220
        ], __CLASS__, __FUNCTION__);
221
    }
222
223
    /**
224
     * @param \DateTime|null $startDate
225
     * @param \DateTime|null $endDate
226
     * @param array          $customSearch
227
     * @param int            $year
228
     * @param int            $month
229
     * @param int            $day
230
     * @param int            $week
231
     *
232
     * @return array
233
     */
234
    protected function determineSearch(
235
        \DateTime $startDate = null,
236
        \DateTime $endDate = null,
237
        array $customSearch = [],
238
        $year = null,
239
        $month = null,
240
        $day = null,
241
        $week = null
242
    ) {
243
        $searchMode = false;
244
        if ($startDate || $endDate || !empty($customSearch)) {
245
            $searchMode = true;
246
            $indices = $this->indexRepository->findBySearch($startDate, $endDate, $customSearch);
247
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month) && MathUtility::canBeInterpretedAsInteger($day)) {
248
            $indices = $this->indexRepository->findDay($year, $month, $day);
249
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month)) {
250
            $indices = $this->indexRepository->findMonth($year, $month);
251
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($week)) {
252
            $indices = $this->indexRepository->findWeek($year, $week, $this->settings['weekStart']);
253
        } elseif (MathUtility::canBeInterpretedAsInteger($year)) {
254
            $indices = $this->indexRepository->findYear($year);
255
        } else {
256
            $overrideStartDate = (int) $this->settings['overrideStartdate'];
257
            $overrideEndDate = (int) $this->settings['overrideEnddate'];
258
            $indices = $this->indexRepository->findList(
259
                (int) $this->settings['limit'],
260
                $this->settings['listStartTime'],
261
                (int) $this->settings['listStartTimeOffsetHours'],
262
                $overrideStartDate,
263
                $overrideEndDate
264
            );
265
        }
266
267
        // use this variable in your extension to add more custom variables
268
        $variables = [
269
            'extended' => [
270
                'indices' => $indices,
271
                'searchMode' => $searchMode,
272
                'parameters' => [
273
                    'startDate' => $startDate,
274
                    'endDate' => $endDate,
275
                    'customSearch' => $customSearch,
276
                    'year' => $year,
277
                    'month' => $month,
278
                    'day' => $day,
279
                    'week' => $week,
280
                ],
281
            ],
282
        ];
283
        $variables['settings'] = $this->settings;
284
285
        $dispatcher = $this->objectManager->get(Dispatcher::class);
286
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
287
288
        return $variables['extended'];
289
    }
290
291
    /**
292
     * Year action.
293
     *
294
     * @param int $year
295
     */
296
    public function yearAction($year = null)
297
    {
298
        $date = DateTimeUtility::normalizeDateTime(1, 1, $year);
299
300
        $this->slotExtendedAssignMultiple([
301
            'indices' => $this->indexRepository->findYear($date->format('Y')),
302
            'date' => $date,
303
        ], __CLASS__, __FUNCTION__);
304
    }
305
306
    /**
307
     * Month action.
308
     *
309
     * @param int $year
310
     * @param int $month
311
     * @param int $day
312
     */
313
    public function monthAction($year = null, $month = null, $day = null)
314
    {
315
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
316
317
        $this->slotExtendedAssignMultiple([
318
            'date' => $date,
319
            'indices' => $this->indexRepository->findMonth($date->format('Y'), $date->format('n')),
320
        ], __CLASS__, __FUNCTION__);
321
    }
322
323
    /**
324
     * Week action.
325
     *
326
     * @param int $year
327
     * @param int $week
328
     */
329
    public function weekAction($year = null, $week = null)
330
    {
331
        $now = DateTimeUtility::getNow();
332
        if ($year === null) {
333
            $year = $now->format('o'); // 'o' instead of 'Y': http://php.net/manual/en/function.date.php#106974
334
        }
335
        if ($week === null) {
336
            $week = $now->format('W');
337
        }
338
        $weekStart = (int) $this->settings['weekStart'];
339
        $firstDay = DateTimeUtility::convertWeekYear2DayMonthYear((int) $week, $year, $weekStart);
340
        $timezone = DateTimeUtility::getTimeZone();
341
        $firstDay->setTimezone($timezone);
342
        $firstDay->setTime(0, 0, 0);
343
344
        $weekConfiguration = [
345
            '+0 day' => 2,
346
            '+1 days' => 2,
347
            '+2 days' => 2,
348
            '+3 days' => 2,
349
            '+4 days' => 2,
350
            '+5 days' => 1,
351
            '+6 days' => 1,
352
        ];
353
354
        $this->slotExtendedAssignMultiple([
355
            'firstDay' => $firstDay,
356
            'indices' => $this->indexRepository->findWeek($year, $week, $this->settings['weekStart']),
357
            'weekConfiguration' => $weekConfiguration,
358
        ], __CLASS__, __FUNCTION__);
359
    }
360
361
    /**
362
     * Day action.
363
     *
364
     * @param int $year
365
     * @param int $month
366
     * @param int $day
367
     */
368
    public function dayAction($year = null, $month = null, $day = null)
369
    {
370
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
371
        $date->modify('+12 hours');
372
373
        $previous = clone $date;
374
        $previous->modify('-1 day');
375
376
        $next = clone $date;
377
        $next->modify('+1 day');
378
379
        $this->slotExtendedAssignMultiple([
380
            'indices' => $this->indexRepository->findDay($date->format('Y'), $date->format('n'), $date->format('j')),
381
            'today' => $date,
382
            'previous' => $previous,
383
            'next' => $next,
384
        ], __CLASS__, __FUNCTION__);
385
    }
386
387
    /**
388
     * Detail action.
389
     *
390
     * @param \HDNET\Calendarize\Domain\Model\Index $index
391
     *
392
     * @return string
393
     */
394
    public function detailAction(Index $index = null)
395
    {
396
        if ($index === null) {
397
            // handle fallback for "strange language settings"
398
            if ($this->request->hasArgument('index')) {
399
                $indexId = (int) $this->request->getArgument('index');
400
                if ($indexId > 0) {
401
                    $index = $this->indexRepository->findByUid($indexId);
402
                }
403
            }
404
405
            if ($index === null) {
406
                if (!MathUtility::canBeInterpretedAsInteger($this->settings['listPid'])) {
407
                    return (string) TranslateUtility::get('noEventDetailView');
408
                }
409
                $this->slottedRedirect(__CLASS__, __FUNCTION__ . 'noEvent');
410
            }
411
        }
412
413
        $this->slotExtendedAssignMultiple([
414
            'index' => $index,
415
            'domain' => GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'),
416
        ], __CLASS__, __FUNCTION__);
417
418
        return $this->view->render();
419
    }
420
421
    /**
422
     * Render the search view.
423
     *
424
     * @param \DateTime $startDate
425
     * @param \DateTime $endDate
426
     * @param array     $customSearch
427
     *
428
     * @ignorevalidation $startDate
429
     * @ignorevalidation $endDate
430
     * @ignorevalidation $customSearch
431
     */
432
    public function searchAction(\DateTime $startDate = null, \DateTime $endDate = null, array $customSearch = [])
433
    {
434
        $baseDate = DateTimeUtility::getNow();
435
        if (!($startDate instanceof \DateTimeInterface)) {
436
            $startDate = clone $baseDate;
437
        }
438
        if (!($endDate instanceof \DateTimeInterface)) {
439
            $baseDate->modify($this->settings['searchEndModifier']);
440
            $endDate = $baseDate;
441
        }
442
443
        $this->slotExtendedAssignMultiple([
444
            'startDate' => $startDate,
445
            'endDate' => $endDate,
446
            'customSearch' => $customSearch,
447
            'configurations' => $this->getCurrentConfigurations(),
448
        ], __CLASS__, __FUNCTION__);
449
    }
450
451
    /**
452
     * Render single items.
453
     */
454
    public function singleAction()
455
    {
456
        $indicies = [];
457
458
        // prepare selection
459
        $selection = [];
460
        $configurations = $this->getCurrentConfigurations();
461
        foreach (GeneralUtility::trimExplode(',', $this->settings['singleItems']) as $item) {
462
            list($table, $uid) = BackendUtility::splitTable_Uid($item);
463
            foreach ($configurations as $configuration) {
464
                if ($configuration['tableName'] === $table) {
465
                    $selection[] = [
466
                        'configuration' => $configuration,
467
                        'uid' => $uid,
468
                    ];
469
                    break;
470
                }
471
            }
472
        }
473
474
        // fetch index
475
        foreach ($selection as $selection) {
476
            $this->indexRepository->setIndexTypes([$selection['configuration']['uniqueRegisterKey']]);
477
            $dummyIndex = new Index();
478
            $dummyIndex->setForeignTable($selection['configuration']['tableName']);
479
            $dummyIndex->setForeignUid($selection['uid']);
480
481
            $result = $this->indexRepository->findByTraversing($dummyIndex);
482
            $index = $result->getQuery()->setLimit(1)->execute()->getFirst();
483
            if (is_object($index)) {
484
                $indicies[] = $index;
485
            }
486
        }
487
488
        $this->slotExtendedAssignMultiple([
489
            'indicies' => $indicies,
490
            'configurations' => $configurations,
491
        ], __CLASS__, __FUNCTION__);
492
    }
493
494
    /**
495
     * Get the allowed actions.
496
     *
497
     * @return array
498
     */
499
    protected function getAllowedActions()
500
    {
501
        $configuration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
502
        $allowedActions = [];
503
        foreach ($configuration['controllerConfiguration'] as $controllerName => $controllerActions) {
504
            $allowedActions[$controllerName] = $controllerActions['actions'];
505
        }
506
507
        return $allowedActions['Calendar'] ?? [];
508
    }
509
510
    /**
511
     * Get the current configurations.
512
     *
513
     * @return array
514
     */
515
    protected function getCurrentConfigurations()
516
    {
517
        $configurations = GeneralUtility::trimExplode(',', $this->settings['configuration'], true);
518
        $return = [];
519
        foreach (Register::getRegister() as $key => $configuration) {
520
            if (in_array($key, $configurations)) {
521
                $return[] = $configuration;
522
            }
523
        }
524
525
        return $return;
526
    }
527
528
    /**
529
     * A redirect that have a slot included.
530
     *
531
     * @param string $signalClassName name of the signal class: __CLASS__
532
     * @param string $signalName name of the signal: __FUNCTION__
533
     * @param array $variables optional: if not set use the defaults
534
     */
535
    protected function slottedRedirect($signalClassName, $signalName, $variables = null)
536
    {
537
        // set default variables for the redirect
538
        if ($variables === null) {
539
            $variables['extended'] = [
540
                'actionName'     => 'list',
541
                'controllerName' => null,
542
                'extensionName'  => null,
543
                'arguments'      => [],
544
                'pageUid'        => $this->settings['listPid'],
545
                'delay'          => 0,
546
                'statusCode'     => 301
547
            ];
548
            $variables['extended']['pluginHmac'] = $this->calculatePluginHmac();
549
            $variables['settings'] = $this->settings;
550
        }
551
552
        $dispatcher = $this->objectManager->get(Dispatcher::class);
553
        $variables = $dispatcher->dispatch($signalClassName, $signalName, $variables);
554
555
        $this->redirect(
556
            $variables['extended']['actionName'],
557
            $variables['extended']['controllerName'],
558
            $variables['extended']['extensionName'],
559
            $variables['extended']['arguments'],
560
            $variables['extended']['pageUid'],
561
            $variables['extended']['delay'],
562
            $variables['extended']['statusCode']
563
        );
564
    }
565
}
566