Completed
Push — master ( c73141...490d99 )
by Tim
04:55 queued 02:37
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
/**
4
 * Calendar.
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\Controller;
9
10
use HDNET\Calendarize\Domain\Model\Index;
11
use HDNET\Calendarize\Register;
12
use HDNET\Calendarize\Utility\DateTimeUtility;
13
use HDNET\Calendarize\Utility\EventUtility;
14
use HDNET\Calendarize\Utility\ExtensionConfigurationUtility;
15
use HDNET\Calendarize\Utility\TranslateUtility;
16
use TYPO3\CMS\Backend\Utility\BackendUtility;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
use TYPO3\CMS\Core\Utility\MathUtility;
19
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
20
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
21
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
22
23
/**
24
 * Calendar.
25
 */
26
class CalendarController extends AbstractController
27
{
28
    /**
29
     * Init all actions.
30
     */
31
    public function initializeAction()
32
    {
33
        parent::initializeAction();
34
        $this->indexRepository->setIndexTypes(GeneralUtility::trimExplode(',', $this->settings['configuration'], true));
35
        $additionalSlotArguments = [
36
            'contentRecord' => $this->configurationManager->getContentObject()->data,
37
            'settings' => $this->settings,
38
        ];
39
        $this->indexRepository->setAdditionalSlotArguments($additionalSlotArguments);
40
41
        if (isset($this->settings['sorting'])) {
42
            if (isset($this->settings['sortBy'])) {
43
                $this->indexRepository->setDefaultSortingDirection($this->settings['sorting'], $this->settings['sortBy']);
44
            } else {
45
                $this->indexRepository->setDefaultSortingDirection($this->settings['sorting']);
46
            }
47
        }
48
49
        if (isset($this->arguments['startDate'])) {
50
            $this->arguments['startDate']->getPropertyMappingConfiguration()
51
                ->setTypeConverterOption(
52
                    DateTimeConverter::class,
53
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
54
                    $this->settings['dateFormat']
55
                );
56
        }
57
        if (isset($this->arguments['endDate'])) {
58
            $this->arguments['endDate']->getPropertyMappingConfiguration()
59
                ->setTypeConverterOption(
60
                    DateTimeConverter::class,
61
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
62
                    $this->settings['dateFormat']
63
                );
64
        }
65
        if ($this->request->hasArgument('event') && 'detailAction' === $this->actionMethodName) {
66
            // default configuration
67
            $configurationName = $this->settings['configuration'];
68
            // configuration overwritten by argument?
69
            if ($this->request->hasArgument('extensionConfiguration')) {
70
                $configurationName = $this->request->getArgument('extensionConfiguration');
71
            }
72
            // get the configuration
73
            $configuration = ExtensionConfigurationUtility::get($configurationName);
74
75
            // get Event by Configuration and Uid
76
            $event = EventUtility::getOriginalRecordByConfiguration($configuration, (int) $this->request->getArgument('event'));
77
            $index = $this->indexRepository->findByEventTraversing($event, true, false, 1)->getFirst();
78
79
            // if there is a valid index in the event
80
            if ($index) {
81
                $this->redirect('detail', null, null, ['index' => $index]);
82
            }
83
        }
84
    }
85
86
    /**
87
     * Latest action.
88
     *
89
     * @param \HDNET\Calendarize\Domain\Model\Index $index
90
     * @param \DateTime                             $startDate
91
     * @param \DateTime                             $endDate
92
     * @param array                                 $customSearch *
93
     * @param int                                   $year
94
     * @param int                                   $month
95
     * @param int                                   $week
96
     *
97
     * @ignorevalidation $startDate
98
     * @ignorevalidation $endDate
99
     * @ignorevalidation $customSearch
100
     *
101
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
102
     */
103
    public function latestAction(
104
        Index $index = null,
105
        \DateTime $startDate = null,
106
        \DateTime $endDate = null,
107
        array $customSearch = [],
108
        $year = null,
109
        $month = null,
110
        $week = null
111
    ) {
112
        $this->checkStaticTemplateIsIncluded();
113
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
114
            $this->forward('detail');
115
        }
116
117
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
118
119
        $this->slotExtendedAssignMultiple([
120
            'indices' => $search['indices'],
121
            'searchMode' => $search['searchMode'],
122
            'searchParameter' => [
123
                'startDate' => $startDate,
124
                'endDate' => $endDate,
125
                'customSearch' => $customSearch,
126
                'year' => $year,
127
                'month' => $month,
128
                'week' => $week,
129
            ],
130
        ], __CLASS__, __FUNCTION__);
131
    }
132
133
    /**
134
     * Result action.
135
     *
136
     * @param \HDNET\Calendarize\Domain\Model\Index $index
137
     * @param \DateTime                             $startDate
138
     * @param \DateTime                             $endDate
139
     * @param array                                 $customSearch
140
     * @param int                                   $year
141
     * @param int                                   $month
142
     * @param int                                   $week
143
     *
144
     * @ignorevalidation $startDate
145
     * @ignorevalidation $endDate
146
     * @ignorevalidation $customSearch
147
     *
148
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
149
     */
150
    public function resultAction(
151
        Index $index = null,
152
        \DateTime $startDate = null,
153
        \DateTime $endDate = null,
154
        array $customSearch = [],
155
        $year = null,
156
        $month = null,
157
        $week = null
158
    ) {
159
        $this->checkStaticTemplateIsIncluded();
160
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
161
            $this->forward('detail');
162
        }
163
164
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
165
166
        $this->slotExtendedAssignMultiple([
167
            'indices' => $search['indices'],
168
            'searchMode' => $search['searchMode'],
169
            'searchParameter' => [
170
                'startDate' => $startDate,
171
                'endDate' => $endDate,
172
                'customSearch' => $customSearch,
173
                'year' => $year,
174
                'month' => $month,
175
                'week' => $week,
176
            ],
177
        ], __CLASS__, __FUNCTION__);
178
    }
179
180
    /**
181
     * List action.
182
     *
183
     * @param \HDNET\Calendarize\Domain\Model\Index $index
184
     * @param \DateTime                             $startDate
185
     * @param \DateTime                             $endDate
186
     * @param array                                 $customSearch *
187
     * @param int                                   $year
188
     * @param int                                   $month
189
     * @param int                                   $day
190
     * @param int                                   $week
191
     *
192
     * @ignorevalidation $startDate
193
     * @ignorevalidation $endDate
194
     * @ignorevalidation $customSearch
195
     *
196
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
197
     */
198
    public function listAction(
199
        Index $index = null,
200
        \DateTime $startDate = null,
201
        \DateTime $endDate = null,
202
        array $customSearch = [],
203
        $year = null,
204
        $month = null,
205
        $day = null,
206
        $week = null
207
    ) {
208
        $this->checkStaticTemplateIsIncluded();
209
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
210
            $this->forward('detail');
211
        }
212
213
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, $day, $week);
214
215
        $this->slotExtendedAssignMultiple([
216
            'indices' => $search['indices'],
217
            'searchMode' => $search['searchMode'],
218
            'searchParameter' => [
219
                'startDate' => $startDate,
220
                'endDate' => $endDate,
221
                'customSearch' => $customSearch,
222
                'year' => $year,
223
                'month' => $month,
224
                'day' => $day,
225
                'week' => $week,
226
            ],
227
        ], __CLASS__, __FUNCTION__);
228
    }
229
230
    /**
231
     * Past action.
232
     *
233
     * @param int        $limit
234
     * @param string     $sort
235
     *
236
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
237
     */
238
239
    public function pastAction(
240
        $limit = 100,
0 ignored issues
show
Unused Code introduced by
The parameter $limit is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
241
        $sort = 'ASC'
0 ignored issues
show
Unused Code introduced by
The parameter $sort is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
242
    ) {
243
        $limit = intval($this->settings['limit']);
244
        $sort = $this->settings['sorting'];
245
        $this->checkStaticTemplateIsIncluded();
246
        $this->slotExtendedAssignMultiple([
247
           'indices' => $this->indexRepository->findByPast($limit, $sort)
248
        ], __CLASS__, __FUNCTION__);
249
    }
250
251
252
    /**
253
     * Year action.
254
     *
255
     * @param int $year
256
     */
257
    public function yearAction($year = null)
258
    {
259
        $date = DateTimeUtility::normalizeDateTime(1, 1, $year);
260
261
        $this->slotExtendedAssignMultiple([
262
            'indices' => $this->indexRepository->findYear($date->format('Y')),
263
            'date' => $date,
264
        ], __CLASS__, __FUNCTION__);
265
    }
266
267
    /**
268
     * Month action.
269
     *
270
     * @param int $year
271
     * @param int $month
272
     * @param int $day
273
     */
274
    public function monthAction($year = null, $month = null, $day = null)
275
    {
276
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
277
278
        $this->slotExtendedAssignMultiple([
279
            'date' => $date,
280
            'indices' => $this->indexRepository->findMonth((int)$date->format('Y'), (int)$date->format('n')),
281
        ], __CLASS__, __FUNCTION__);
282
    }
283
284
    /**
285
     * Week action.
286
     *
287
     * @param int $year
288
     * @param int $week
289
     */
290
    public function weekAction($year = null, $week = null)
291
    {
292
        $now = DateTimeUtility::getNow();
293
        if (null === $year) {
294
            $year = $now->format('o'); // 'o' instead of 'Y': http://php.net/manual/en/function.date.php#106974
295
        }
296
        if (null === $week) {
297
            $week = $now->format('W');
298
        }
299
        $weekStart = (int) $this->settings['weekStart'];
300
        $firstDay = DateTimeUtility::convertWeekYear2DayMonthYear((int) $week, $year, $weekStart);
301
        $timezone = DateTimeUtility::getTimeZone();
302
        $firstDay->setTimezone($timezone);
303
        $firstDay->setTime(0, 0, 0);
304
305
        $weekConfiguration = [
306
            '+0 day' => 2,
307
            '+1 days' => 2,
308
            '+2 days' => 2,
309
            '+3 days' => 2,
310
            '+4 days' => 2,
311
            '+5 days' => 1,
312
            '+6 days' => 1,
313
        ];
314
315
        $this->slotExtendedAssignMultiple([
316
            'firstDay' => $firstDay,
317
            'indices' => $this->indexRepository->findWeek($year, $week, $this->settings['weekStart']),
318
            'weekConfiguration' => $weekConfiguration,
319
        ], __CLASS__, __FUNCTION__);
320
    }
321
322
    /**
323
     * Day action.
324
     *
325
     * @param int $year
326
     * @param int $month
327
     * @param int $day
328
     */
329
    public function dayAction($year = null, $month = null, $day = null)
330
    {
331
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
332
        $date->modify('+12 hours');
333
334
        $previous = clone $date;
335
        $previous->modify('-1 day');
336
337
        $next = clone $date;
338
        $next->modify('+1 day');
339
340
        $this->slotExtendedAssignMultiple([
341
            'indices' => $this->indexRepository->findDay($date->format('Y'), $date->format('n'), $date->format('j')),
342
            'today' => $date,
343
            'previous' => $previous,
344
            'next' => $next,
345
        ], __CLASS__, __FUNCTION__);
346
    }
347
348
    /**
349
     * Detail action.
350
     *
351
     * @param \HDNET\Calendarize\Domain\Model\Index $index
352
     *
353
     * @return string
354
     */
355
    public function detailAction(Index $index = null)
356
    {
357
        if (null === $index) {
358
            // handle fallback for "strange language settings"
359
            if ($this->request->hasArgument('index')) {
360
                $indexId = (int) $this->request->getArgument('index');
361
                if ($indexId > 0) {
362
                    $index = $this->indexRepository->findByUid($indexId);
363
                }
364
            }
365
366
            if (null === $index) {
367
                if (!MathUtility::canBeInterpretedAsInteger($this->settings['listPid'])) {
368
                    return (string) TranslateUtility::get('noEventDetailView');
369
                }
370
                $this->slottedRedirect(__CLASS__, __FUNCTION__ . 'noEvent');
371
            }
372
        }
373
374
        $this->slotExtendedAssignMultiple([
375
            'index' => $index,
376
            'domain' => GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'),
377
        ], __CLASS__, __FUNCTION__);
378
379
        return $this->view->render();
380
    }
381
382
    /**
383
     * Render the search view.
384
     *
385
     * @param \DateTime $startDate
386
     * @param \DateTime $endDate
387
     * @param array     $customSearch
388
     *
389
     * @ignorevalidation $startDate
390
     * @ignorevalidation $endDate
391
     * @ignorevalidation $customSearch
392
     */
393
    public function searchAction(\DateTime $startDate = null, \DateTime $endDate = null, array $customSearch = [])
394
    {
395
        $baseDate = DateTimeUtility::getNow();
396
        if (!($startDate instanceof \DateTimeInterface)) {
397
            $startDate = clone $baseDate;
398
        }
399
        if (!($endDate instanceof \DateTimeInterface)) {
400
            $baseDate->modify($this->settings['searchEndModifier']);
401
            $endDate = $baseDate;
402
        }
403
404
        $this->slotExtendedAssignMultiple([
405
            'startDate' => $startDate,
406
            'endDate' => $endDate,
407
            'customSearch' => $customSearch,
408
            'configurations' => $this->getCurrentConfigurations(),
409
        ], __CLASS__, __FUNCTION__);
410
    }
411
412
    /**
413
     * Render single items.
414
     */
415
    public function singleAction()
416
    {
417
        $indicies = [];
418
419
        // prepare selection
420
        $selection = [];
421
        $configurations = $this->getCurrentConfigurations();
422
        foreach (GeneralUtility::trimExplode(',', $this->settings['singleItems']) as $item) {
423
            list($table, $uid) = BackendUtility::splitTable_Uid($item);
424
            foreach ($configurations as $configuration) {
425
                if ($configuration['tableName'] === $table) {
426
                    $selection[] = [
427
                        'configuration' => $configuration,
428
                        'uid' => $uid,
429
                    ];
430
                    break;
431
                }
432
            }
433
        }
434
435
        // fetch index
436
        foreach ($selection as $selection) {
437
            $this->indexRepository->setIndexTypes([$selection['configuration']['uniqueRegisterKey']]);
438
            $dummyIndex = new Index();
439
            $dummyIndex->setForeignTable($selection['configuration']['tableName']);
440
            $dummyIndex->setForeignUid($selection['uid']);
441
442
            $result = $this->indexRepository->findByTraversing($dummyIndex);
443
            $index = $result->getQuery()->setLimit(1)->execute()->getFirst();
444
            if (\is_object($index)) {
445
                $indicies[] = $index;
446
            }
447
        }
448
449
        $this->slotExtendedAssignMultiple([
450
            'indicies' => $indicies,
451
            'configurations' => $configurations,
452
        ], __CLASS__, __FUNCTION__);
453
    }
454
455
    /**
456
     * Build the search structure.
457
     *
458
     * @param \DateTime|null $startDate
459
     * @param \DateTime|null $endDate
460
     * @param array          $customSearch
461
     * @param int            $year
462
     * @param int            $month
463
     * @param int            $day
464
     * @param int            $week
465
     *
466
     * @return array
467
     */
468
    protected function determineSearch(
469
        \DateTime $startDate = null,
470
        \DateTime $endDate = null,
471
        array $customSearch = [],
472
        $year = null,
473
        $month = null,
474
        $day = null,
475
        $week = null
476
    ) {
477
        $searchMode = false;
478
        if ($startDate || $endDate || !empty($customSearch)) {
479
            $searchMode = true;
480
            $indices = $this->indexRepository->findBySearch($startDate, $endDate, $customSearch);
481
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month) && MathUtility::canBeInterpretedAsInteger($day)) {
482
            $indices = $this->indexRepository->findDay($year, $month, $day);
483
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month)) {
484
            $indices = $this->indexRepository->findMonth((int)$year, (int)$month);
485
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($week)) {
486
            $indices = $this->indexRepository->findWeek($year, $week, $this->settings['weekStart']);
487
        } elseif (MathUtility::canBeInterpretedAsInteger($year)) {
488
            $indices = $this->indexRepository->findYear($year);
489
        } else {
490
            $overrideStartDate = (int) $this->settings['overrideStartdate'];
491
            $overrideEndDate = (int) $this->settings['overrideEnddate'];
492
            $indices = $this->indexRepository->findList(
493
                (int) $this->settings['limit'],
494
                $this->settings['listStartTime'],
495
                (int) $this->settings['listStartTimeOffsetHours'],
496
                $overrideStartDate,
497
                $overrideEndDate
498
            );
499
        }
500
501
        // use this variable in your extension to add more custom variables
502
        $variables = [
503
            'extended' => [
504
                'indices' => $indices,
505
                'searchMode' => $searchMode,
506
                'parameters' => [
507
                    'startDate' => $startDate,
508
                    'endDate' => $endDate,
509
                    'customSearch' => $customSearch,
510
                    'year' => $year,
511
                    'month' => $month,
512
                    'day' => $day,
513
                    'week' => $week,
514
                ],
515
            ],
516
        ];
517
        $variables['settings'] = $this->settings;
518
519
        $dispatcher = $this->objectManager->get(Dispatcher::class);
520
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
521
522
        return $variables['extended'];
523
    }
524
525
    /**
526
     * Get the allowed actions.
527
     *
528
     * @return array
529
     */
530
    protected function getAllowedActions()
531
    {
532
        $configuration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
533
        $allowedActions = [];
534
        foreach ($configuration['controllerConfiguration'] as $controllerName => $controllerActions) {
535
            $allowedActions[$controllerName] = $controllerActions['actions'];
536
        }
537
538
        return $allowedActions['Calendar'] ?? [];
539
    }
540
541
    /**
542
     * Get the current configurations.
543
     *
544
     * @return array
545
     */
546
    protected function getCurrentConfigurations()
547
    {
548
        $configurations = GeneralUtility::trimExplode(',', $this->settings['configuration'], true);
549
        $return = [];
550
        foreach (Register::getRegister() as $key => $configuration) {
551
            if (\in_array($key, $configurations, true)) {
552
                $return[] = $configuration;
553
            }
554
        }
555
556
        return $return;
557
    }
558
559
    /**
560
     * A redirect that have a slot included.
561
     *
562
     * @param string $signalClassName name of the signal class: __CLASS__
563
     * @param string $signalName      name of the signal: __FUNCTION__
564
     * @param array  $variables       optional: if not set use the defaults
565
     */
566
    protected function slottedRedirect($signalClassName, $signalName, $variables = null)
567
    {
568
        // set default variables for the redirect
569
        if (null === $variables) {
570
            $variables['extended'] = [
571
                'actionName' => 'list',
572
                'controllerName' => null,
573
                'extensionName' => null,
574
                'arguments' => [],
575
                'pageUid' => $this->settings['listPid'],
576
                'delay' => 0,
577
                'statusCode' => 301,
578
            ];
579
            $variables['extended']['pluginHmac'] = $this->calculatePluginHmac();
580
            $variables['settings'] = $this->settings;
581
        }
582
583
        $dispatcher = $this->objectManager->get(Dispatcher::class);
584
        $variables = $dispatcher->dispatch($signalClassName, $signalName, $variables);
585
586
        $this->redirect(
587
            $variables['extended']['actionName'],
588
            $variables['extended']['controllerName'],
589
            $variables['extended']['extensionName'],
590
            $variables['extended']['arguments'],
591
            $variables['extended']['pageUid'],
592
            $variables['extended']['delay'],
593
            $variables['extended']['statusCode']
594
        );
595
    }
596
}
597