Completed
Push — master ( 7d6874...e6bb62 )
by Tim
02:12
created

CalendarController::listAction()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

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