Completed
Push — master ( 54c481...7b9104 )
by Tim
02:32 queued 11s
created

CalendarController::getPagination()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 4
nop 1
1
<?php
2
3
/**
4
 * Calendar.
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\Controller;
9
10
use GeorgRinger\NumberedPagination\NumberedPagination;
11
use HDNET\Calendarize\Domain\Model\Event;
12
use HDNET\Calendarize\Domain\Model\Index;
13
use HDNET\Calendarize\Register;
14
use HDNET\Calendarize\Utility\DateTimeUtility;
15
use HDNET\Calendarize\Utility\EventUtility;
16
use HDNET\Calendarize\Utility\ExtensionConfigurationUtility;
17
use HDNET\Calendarize\Utility\TranslateUtility;
18
use TYPO3\CMS\Backend\Utility\BackendUtility;
19
use TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry;
20
use TYPO3\CMS\Core\Pagination\SimplePagination;
21
use TYPO3\CMS\Core\Utility\ClassNamingUtility;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Core\Utility\MathUtility;
24
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
25
use TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface;
26
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
27
use TYPO3\CMS\Extbase\Pagination\QueryResultPaginator;
28
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
29
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;
30
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
31
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
32
33
/**
34
 * Calendar.
35
 */
36
class CalendarController extends AbstractController
37
{
38
    /**
39
     * @var ObjectManagerInterface
40
     */
41
    protected $objectManager;
42
43
    public function __construct(ObjectManagerInterface $objectManager)
44
    {
45
        $this->objectManager = $objectManager;
46
    }
47
48
    /**
49
     * Init all actions.
50
     */
51
    public function initializeAction()
52
    {
53
        $this->addCacheTags(['calendarize']);
54
55
        parent::initializeAction();
56
        if (isset($this->settings['format'])) {
57
            $this->request->setFormat($this->settings['format']);
58
        }
59
        $this->indexRepository->setIndexTypes(GeneralUtility::trimExplode(',', $this->settings['configuration'], true));
60
        $additionalSlotArguments = [
61
            'contentRecord' => $this->configurationManager->getContentObject()->data,
62
            'settings' => $this->settings,
63
        ];
64
        $this->indexRepository->setAdditionalSlotArguments($additionalSlotArguments);
65
66
        if (isset($this->settings['sorting'])) {
67
            if (isset($this->settings['sortBy'])) {
68
                $this->indexRepository->setDefaultSortingDirection($this->settings['sorting'], $this->settings['sortBy']);
69
            } else {
70
                $this->indexRepository->setDefaultSortingDirection($this->settings['sorting']);
71
            }
72
        }
73
74
        if (isset($this->arguments['startDate'])) {
75
            $this->arguments['startDate']->getPropertyMappingConfiguration()
76
                ->setTypeConverterOption(
77
                    DateTimeConverter::class,
78
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
79
                    'Y-m-d'
80
                );
81
        }
82
        if (isset($this->arguments['endDate'])) {
83
            $this->arguments['endDate']->getPropertyMappingConfiguration()
84
                ->setTypeConverterOption(
85
                    DateTimeConverter::class,
86
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
87
                    'Y-m-d'
88
                );
89
        }
90
        if ($this->request->hasArgument('event') && 'detailAction' === $this->actionMethodName) {
91
            // default configuration
92
            $configurationName = $this->settings['configuration'];
93
            // configuration overwritten by argument?
94
            if ($this->request->hasArgument('extensionConfiguration')) {
95
                $configurationName = $this->request->getArgument('extensionConfiguration');
96
            }
97
            // get the configuration
98
            $configuration = ExtensionConfigurationUtility::get($configurationName);
99
100
            // get Event by Configuration and Uid
101
            $event = EventUtility::getOriginalRecordByConfiguration($configuration, (int)$this->request->getArgument('event'));
102
            $index = $this->indexRepository->findByEventTraversing($event, true, false, 1)->getFirst();
103
104
            // if there is a valid index in the event
105
            if ($index) {
106
                $this->redirect('detail', null, null, ['index' => $index]);
107
            }
108
        }
109
    }
110
111
    /**
112
     * Latest action.
113
     *
114
     * @param \HDNET\Calendarize\Domain\Model\Index $index
115
     * @param \DateTime                             $startDate
116
     * @param \DateTime                             $endDate
117
     * @param array                                 $customSearch *
118
     * @param int                                   $year
119
     * @param int                                   $month
120
     * @param int                                   $week
121
     *
122
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $startDate
123
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $endDate
124
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $customSearch
125
     *
126
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
127
     */
128
    public function latestAction(
129
        Index $index = null,
130
        \DateTime $startDate = null,
131
        \DateTime $endDate = null,
132
        array $customSearch = [],
133
        $year = null,
134
        $month = null,
135
        $week = null
136
    ) {
137
        $this->checkStaticTemplateIsIncluded();
138
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
139
            $this->forward('detail');
140
        }
141
142
        $this->addCacheTags(['calendarize_latest']);
143
144
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
145
146
        $this->slotExtendedAssignMultiple([
147
            'indices' => $search['indices'],
148
            'pagination' => $this->getPagination($search['indices']),
149
            'searchMode' => $search['searchMode'],
150
            'searchParameter' => [
151
                'startDate' => $startDate,
152
                'endDate' => $endDate,
153
                'customSearch' => $customSearch,
154
                'year' => $year,
155
                'month' => $month,
156
                'week' => $week,
157
            ],
158
        ], __CLASS__, __FUNCTION__);
159
    }
160
161
    /**
162
     * Result action.
163
     *
164
     * @param \HDNET\Calendarize\Domain\Model\Index $index
165
     * @param \DateTime                             $startDate
166
     * @param \DateTime                             $endDate
167
     * @param array                                 $customSearch
168
     * @param int                                   $year
169
     * @param int                                   $month
170
     * @param int                                   $week
171
     *
172
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $startDate
173
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $endDate
174
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $customSearch
175
     *
176
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
177
     */
178
    public function resultAction(
179
        Index $index = null,
180
        \DateTime $startDate = null,
181
        \DateTime $endDate = null,
182
        array $customSearch = [],
183
        $year = null,
184
        $month = null,
185
        $week = null
186
    ) {
187
        $this->checkStaticTemplateIsIncluded();
188
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
189
            $this->forward('detail');
190
        }
191
192
        $this->addCacheTags(['calendarize_result']);
193
194
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, null, $week);
195
196
        $this->slotExtendedAssignMultiple([
197
            'indices' => $search['indices'],
198
            'pagination' => $this->getPagination($search['indices']),
199
            'searchMode' => $search['searchMode'],
200
            'searchParameter' => [
201
                'startDate' => $startDate,
202
                'endDate' => $endDate,
203
                'customSearch' => $customSearch,
204
                'year' => $year,
205
                'month' => $month,
206
                'week' => $week,
207
            ],
208
        ], __CLASS__, __FUNCTION__);
209
    }
210
211
    /**
212
     * List action.
213
     *
214
     * @param \HDNET\Calendarize\Domain\Model\Index $index
215
     * @param \DateTime                             $startDate
216
     * @param \DateTime                             $endDate
217
     * @param array                                 $customSearch *
218
     * @param int                                   $year
219
     * @param int                                   $month
220
     * @param int                                   $day
221
     * @param int                                   $week
222
     *
223
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $startDate
224
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $endDate
225
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $customSearch
226
     *
227
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
228
     */
229
    public function listAction(
230
        Index $index = null,
231
        \DateTime $startDate = null,
232
        \DateTime $endDate = null,
233
        array $customSearch = [],
234
        $year = null,
235
        $month = null,
236
        $day = null,
237
        $week = null
238
    ) {
239
        $this->checkStaticTemplateIsIncluded();
240
        if (($index instanceof Index) && \in_array('detail', $this->getAllowedActions(), true)) {
241
            $this->forward('detail');
242
        }
243
244
        $this->addCacheTags(['calendarize_list']);
245
246
        $search = $this->determineSearch($startDate, $endDate, $customSearch, $year, $month, $day, $week);
247
248
        $this->slotExtendedAssignMultiple([
249
            'indices' => $search['indices'],
250
            'pagination' => $this->getPagination($search['indices']),
251
            'searchMode' => $search['searchMode'],
252
            'searchParameter' => [
253
                'startDate' => $startDate,
254
                'endDate' => $endDate,
255
                'customSearch' => $customSearch,
256
                'year' => $year,
257
                'month' => $month,
258
                'day' => $day,
259
                'week' => $week,
260
            ],
261
        ], __CLASS__, __FUNCTION__);
262
    }
263
264
    /**
265
     * Shortcut.
266
     */
267
    public function shortcutAction()
268
    {
269
        $this->addCacheTags(['calendarize_shortcut']);
270
        list($table, $uid) = explode(':', $GLOBALS['TSFE']->currentRecord);
271
        $register = Register::getRegister();
272
273
        $event = null;
274
        foreach ($register as $key => $value) {
275
            if ($value['tableName'] === $table) {
276
                $repositoryName = ClassNamingUtility::translateModelNameToRepositoryName($value['modelName']);
277
                if (class_exists($repositoryName)) {
278
                    $repository = $this->objectManager->get($repositoryName);
0 ignored issues
show
Deprecated Code introduced by
The method TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated with message: since TYPO3 10.4, will be removed in version 12.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
279
                    $event = $repository->findByUid($uid);
280
281
                    $this->addCacheTags(['calendarize_' . lcfirst($value['uniqueRegisterKey']) . '_' . $event->getUid()]);
282
                    break;
283
                }
284
            }
285
        }
286
287
        if (!($event instanceof DomainObjectInterface)) {
288
            return 'Invalid object';
289
        }
290
291
        $fetchEvent = $this->indexRepository->findByEventTraversing($event, true, false, 1);
292
        if (\count($fetchEvent) <= 0) {
293
            $fetchEvent = $this->indexRepository->findByEventTraversing($event, false, true, 1, QueryInterface::ORDER_DESCENDING);
294
        }
295
296
        $this->view->assignMultiple([
297
            'pagination' => $this->getPagination($fetchEvent),
0 ignored issues
show
Bug introduced by
It seems like $fetchEvent can also be of type array; however, HDNET\Calendarize\Contro...roller::getPagination() does only seem to accept object<TYPO3\CMS\Extbase...e\QueryResultInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
298
            'indices' => $fetchEvent,
299
        ]);
300
    }
301
302
    /**
303
     * Past action.
304
     *
305
     * @param int    $limit
306
     * @param string $sort
307
     *
308
     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
309
     */
310
    public function pastAction(
311
        $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...
312
        $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...
313
    ) {
314
        $this->addCacheTags(['calendarize_past']);
315
316
        $limit = (int)($this->settings['limit']);
317
        $sort = $this->settings['sorting'];
318
        $this->checkStaticTemplateIsIncluded();
319
        $indices = $this->indexRepository->findByPast($limit, $sort);
320
321
        $this->slotExtendedAssignMultiple([
322
            'indices' => $indices,
323
            'pagination' => $this->getPagination($indices),
0 ignored issues
show
Bug introduced by
It seems like $indices defined by $this->indexRepository->findByPast($limit, $sort) on line 319 can also be of type array; however, HDNET\Calendarize\Contro...roller::getPagination() does only seem to accept object<TYPO3\CMS\Extbase...e\QueryResultInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
324
        ], __CLASS__, __FUNCTION__);
325
    }
326
327
    /**
328
     * Year action.
329
     *
330
     * @param int $year
331
     */
332
    public function yearAction($year = null)
333
    {
334
        $this->addCacheTags(['calendarize_year']);
335
336
        // use the thrid day, to avoid time shift problems in the timezone
337
        $date = DateTimeUtility::normalizeDateTime(3, 1, $year);
338
        $now = DateTimeUtility::getNow();
339
        if (null === $year || $now->format('Y') === $date->format('Y')) {
340
            $date = $now;
341
        }
342
343
        if ($this->isDateOutOfTypoScriptConfiguration($date)) {
344
            return $this->return404Page();
345
        }
346
347
        $this->slotExtendedAssignMultiple([
348
            'indices' => $this->indexRepository->findYear((int)$date->format('Y')),
349
            'date' => $date,
350
        ], __CLASS__, __FUNCTION__);
351
    }
352
353
    /**
354
     * Quarter action.
355
     *
356
     * @param int $year
357
     * @param int $quarter 1-4
358
     */
359
    public function quarterAction(int $year = null, int $quarter = null)
360
    {
361
        $this->addCacheTags(['calendarize_quarter']);
362
363
        $quarter = DateTimeUtility::normalizeQuarter($quarter);
364
        $date = DateTimeUtility::normalizeDateTime(1, 1 + (($quarter - 1) * 3), $year);
365
366
        if ($this->isDateOutOfTypoScriptConfiguration($date)) {
367
            return $this->return404Page();
368
        }
369
370
        $this->slotExtendedAssignMultiple([
371
            'indices' => $this->indexRepository->findQuarter((int)$date->format('Y'), $quarter),
372
            'date' => $date,
373
            'quarter' => $quarter,
374
        ], __CLASS__, __FUNCTION__);
375
    }
376
377
    /**
378
     * Month action.
379
     *
380
     * @param int $year
381
     * @param int $month
382
     * @param int $day
383
     */
384
    public function monthAction($year = null, $month = null, $day = null)
385
    {
386
        $this->addCacheTags(['calendarize_month']);
387
388
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
389
        $now = DateTimeUtility::getNow();
390
        $useCurrentDate = $now->format('Y-m') === $date->format('Y-m');
391
        if ($useCurrentDate) {
392
            $date = $now;
393
        }
394
395
        if ($this->isDateOutOfTypoScriptConfiguration($date)) {
396
            return $this->return404Page();
397
        }
398
399
        $this->slotExtendedAssignMultiple([
400
            'date' => $date,
401
            'selectDay' => $useCurrentDate,
402
            'ignoreSelectedDay' => !$useCurrentDate,
403
            'indices' => $this->indexRepository->findMonth((int)$date->format('Y'), (int)$date->format('n')),
404
        ], __CLASS__, __FUNCTION__);
405
    }
406
407
    /**
408
     * Week action.
409
     *
410
     * @param int|null $year
411
     * @param int|null $week
412
     */
413
    public function weekAction(?int $year = null, ?int $week = null)
414
    {
415
        $this->addCacheTags(['calendarize_week']);
416
417
        $now = DateTimeUtility::getNow();
418
        if (null === $year) {
419
            $year = (int)$now->format('o'); // 'o' instead of 'Y': http://php.net/manual/en/function.date.php#106974
420
        }
421
        if (null === $week) {
422
            $week = (int)$now->format('W');
423
        }
424
        $weekStart = (int)$this->settings['weekStart'];
425
        $firstDay = DateTimeUtility::convertWeekYear2DayMonthYear($week, $year, $weekStart);
426
427
        if ($this->isDateOutOfTypoScriptConfiguration($firstDay)) {
428
            return $this->return404Page();
429
        }
430
431
        $weekConfiguration = [
432
            '+0 day' => 2,
433
            '+1 days' => 2,
434
            '+2 days' => 2,
435
            '+3 days' => 2,
436
            '+4 days' => 2,
437
            '+5 days' => 1,
438
            '+6 days' => 1,
439
        ];
440
441
        $this->slotExtendedAssignMultiple([
442
            'firstDay' => $firstDay,
443
            'indices' => $this->indexRepository->findWeek($year, $week, $weekStart),
444
            'weekConfiguration' => $weekConfiguration,
445
        ], __CLASS__, __FUNCTION__);
446
    }
447
448
    /**
449
     * Day action.
450
     *
451
     * @param int $year
452
     * @param int $month
453
     * @param int $day
454
     */
455
    public function dayAction($year = null, $month = null, $day = null)
456
    {
457
        $this->addCacheTags(['calendarize_day']);
458
459
        $date = DateTimeUtility::normalizeDateTime($day, $month, $year);
460
        $date->modify('+12 hours');
461
462
        if ($this->isDateOutOfTypoScriptConfiguration($date)) {
463
            return $this->return404Page();
464
        }
465
466
        $previous = clone $date;
467
        $previous->modify('-1 day');
468
469
        $next = clone $date;
470
        $next->modify('+1 day');
471
472
        $this->slotExtendedAssignMultiple([
473
            'indices' => $this->indexRepository->findDay((int)$date->format('Y'), (int)$date->format('n'), (int)$date->format('j')),
474
            'today' => $date,
475
            'previous' => $previous,
476
            'next' => $next,
477
        ], __CLASS__, __FUNCTION__);
478
    }
479
480
    /**
481
     * Detail action.
482
     *
483
     * @param \HDNET\Calendarize\Domain\Model\Index $index
484
     *
485
     * @return string
486
     */
487
    public function detailAction(Index $index = null)
488
    {
489
        if (null === $index) {
490
            // handle fallback for "strange language settings"
491
            if ($this->request->hasArgument('index')) {
492
                $indexId = (int)$this->request->getArgument('index');
493
                if ($indexId > 0) {
494
                    $index = $this->indexRepository->findByUid($indexId);
495
                }
496
            }
497
498
            if (null === $index) {
499
                if (!MathUtility::canBeInterpretedAsInteger($this->settings['listPid'])) {
500
                    return (string)TranslateUtility::get('noEventDetailView');
501
                }
502
                $this->slottedRedirect(__CLASS__, __FUNCTION__ . 'noEvent');
503
            }
504
        }
505
506
        $this->addCacheTags(['calendarize_detail', 'calendarize_index_' . $index->getUid(), 'calendarize_' . lcfirst($index->getConfiguration()['uniqueRegisterKey']) . '_' . $index->getOriginalObject()->getUid()]);
507
508
        // Meta tags
509
        if ($index->getOriginalObject() instanceof Event) {
510
            // @todo move to event
511
            /** @var Event $event */
512
            $event = $index->getOriginalObject();
513
            GeneralUtility::makeInstance(MetaTagManagerRegistry::class)->getManagerForProperty('og:title')->addProperty('og:title', $event->getTitle());
514
        }
515
516
        $this->slotExtendedAssignMultiple([
517
            'index' => $index,
518
            'domain' => GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'),
519
        ], __CLASS__, __FUNCTION__);
520
521
        return $this->view->render();
522
    }
523
524
    /**
525
     * Render the search view.
526
     *
527
     * @param \DateTime $startDate
528
     * @param \DateTime $endDate
529
     * @param array     $customSearch
530
     *
531
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $startDate
532
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $endDate
533
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation $customSearch
534
     */
535
    public function searchAction(\DateTime $startDate = null, \DateTime $endDate = null, array $customSearch = [])
536
    {
537
        $this->addCacheTags(['calendarize_search']);
538
539
        $baseDate = DateTimeUtility::getNow();
540
        if (!($startDate instanceof \DateTimeInterface)) {
541
            $startDate = clone $baseDate;
542
        }
543
        if (!($endDate instanceof \DateTimeInterface)) {
544
            $endDate = clone $startDate;
545
            $modify = \is_string($this->settings['searchEndModifier']) ? $this->settings['searchEndModifier'] : '+30 days';
546
            $endDate->modify($modify);
547
        }
548
        $this->checkWrongDateOrder($startDate, $endDate);
549
550
        $this->slotExtendedAssignMultiple([
551
            'startDate' => $startDate,
552
            'endDate' => $endDate,
553
            'customSearch' => $customSearch,
554
            'configurations' => $this->getCurrentConfigurations(),
555
        ], __CLASS__, __FUNCTION__);
556
    }
557
558
    /**
559
     * Render single items.
560
     */
561
    public function singleAction()
562
    {
563
        $this->addCacheTags(['calendarize_single']);
564
565
        $indicies = [];
566
567
        // prepare selection
568
        $selections = [];
569
        $configurations = $this->getCurrentConfigurations();
570
        foreach (GeneralUtility::trimExplode(',', $this->settings['singleItems']) as $item) {
571
            list($table, $uid) = BackendUtility::splitTable_Uid($item);
572
            foreach ($configurations as $configuration) {
573
                if ($configuration['tableName'] === $table) {
574
                    $selections[] = [
575
                        'configuration' => $configuration,
576
                        'uid' => $uid,
577
                    ];
578
                    break;
579
                }
580
            }
581
        }
582
583
        // fetch index
584
        foreach ($selections as $selection) {
585
            $this->indexRepository->setIndexTypes([$selection['configuration']['uniqueRegisterKey']]);
586
            $dummyIndex = new Index();
587
            $dummyIndex->setForeignTable($selection['configuration']['tableName']);
588
            $dummyIndex->setForeignUid($selection['uid']);
589
590
            $result = $this->indexRepository->findByTraversing($dummyIndex);
591
            $index = $result->getQuery()->setLimit(1)->execute()->getFirst();
592
            if (\is_object($index)) {
593
                $indicies[] = $index;
594
            } else {
595
                $result = $this->indexRepository->findByTraversing($dummyIndex, false, true);
596
                $index = $result->getQuery()->setLimit(1)->execute()->getFirst();
597
                if (\is_object($index)) {
598
                    $indicies[] = $index;
599
                }
600
            }
601
        }
602
603
        $this->slotExtendedAssignMultiple([
604
            'indicies' => $indicies,
605
            'configurations' => $configurations,
606
        ], __CLASS__, __FUNCTION__);
607
    }
608
609
    /**
610
     * Build the search structure.
611
     *
612
     * @param \DateTime|null $startDate
613
     * @param \DateTime|null $endDate
614
     * @param array          $customSearch
615
     * @param int            $year
616
     * @param int            $month
617
     * @param int            $day
618
     * @param int            $week
619
     *
620
     * @return array
621
     */
622
    protected function determineSearch(
623
        \DateTime $startDate = null,
624
        \DateTime $endDate = null,
625
        array $customSearch = [],
626
        $year = null,
627
        $month = null,
628
        $day = null,
629
        $week = null
630
    ) {
631
        $searchMode = false;
632
        $this->checkWrongDateOrder($startDate, $endDate);
633
        if ($startDate || $endDate || !empty($customSearch)) {
634
            $searchMode = true;
635
            $limit = isset($this->settings['limit']) ? (int)$this->settings['limit'] : 0;
636
            $indices = $this->indexRepository->findBySearch($startDate, $endDate, $customSearch, $limit);
637
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month) && MathUtility::canBeInterpretedAsInteger($day)) {
638
            $indices = $this->indexRepository->findDay((int)$year, (int)$month, (int)$day);
639
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($month)) {
640
            $indices = $this->indexRepository->findMonth((int)$year, (int)$month);
641
        } elseif (MathUtility::canBeInterpretedAsInteger($year) && MathUtility::canBeInterpretedAsInteger($week)) {
642
            $indices = $this->indexRepository->findWeek((int)$year, (int)$week, (int)$this->settings['weekStart']);
643
        } elseif (MathUtility::canBeInterpretedAsInteger($year)) {
644
            $indices = $this->indexRepository->findYear((int)$year);
645
        } else {
646
            // check if relative dates are enabled
647
            if ((bool)$this->settings['useRelativeDate']) {
648
                $overrideStartDateRelative = trim($this->settings['overrideStartRelative']);
649
                if ('' === $overrideStartDateRelative) {
650
                    $overrideStartDateRelative = 'now';
651
                }
652
                try {
653
                    $relativeDate = new \DateTime($overrideStartDateRelative);
654
                } catch (\Exception $e) {
655
                    $relativeDate = DateTimeUtility::getNow();
656
                }
657
                $overrideStartDate = $relativeDate->getTimestamp();
658
                $overrideEndDate = 0;
659
                $overrideEndDateRelative = trim($this->settings['overrideEndRelative']);
660
                if ('' !== $overrideStartDateRelative) {
661
                    try {
662
                        $relativeDate->modify($overrideEndDateRelative);
663
                        $overrideEndDate = $relativeDate->getTimestamp();
664
                    } catch (\Exception $e) {
665
                        // do nothing $overrideEndDate is 0
666
                    }
667
                }
668
            } else {
669
                $overrideStartDate = (int)$this->settings['overrideStartdate'];
670
                $overrideEndDate = (int)$this->settings['overrideEnddate'];
671
            }
672
            $indices = $this->indexRepository->findList(
673
                (int)$this->settings['limit'],
674
                $this->settings['listStartTime'],
675
                (int)$this->settings['listStartTimeOffsetHours'],
676
                $overrideStartDate,
677
                $overrideEndDate
678
            );
679
        }
680
681
        // use this variable in your extension to add more custom variables
682
        $variables = [
683
            'extended' => [
684
                'indices' => $indices,
685
                'searchMode' => $searchMode,
686
                'parameters' => [
687
                    'startDate' => $startDate,
688
                    'endDate' => $endDate,
689
                    'customSearch' => $customSearch,
690
                    'year' => $year,
691
                    'month' => $month,
692
                    'day' => $day,
693
                    'week' => $week,
694
                ],
695
            ],
696
        ];
697
        $variables['settings'] = $this->settings;
698
699
        $dispatcher = $this->objectManager->get(Dispatcher::class);
0 ignored issues
show
Deprecated Code introduced by
The method TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated with message: since TYPO3 10.4, will be removed in version 12.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
700
        $variables = $dispatcher->dispatch(__CLASS__, __FUNCTION__, $variables);
701
702
        return $variables['extended'];
703
    }
704
705
    protected function checkWrongDateOrder(\DateTime &$startDate = null, \DateTime &$endDate = null)
706
    {
707
        if ($startDate && $endDate && $endDate < $startDate) {
708
            // End date is before start date. So use start and end equals!
709
            $endDate = clone $startDate;
710
        }
711
    }
712
713
    /**
714
     * Creates the pagination logic for the results.
715
     *
716
     * @param QueryResultInterface $queryResult
717
     *
718
     * @return array
719
     */
720
    protected function getPagination(QueryResultInterface $queryResult): array
721
    {
722
        $paginateConfiguration = $this->settings['paginateConfiguration'] ?? [];
723
        $itemsPerPage = (int)($paginateConfiguration['itemsPerPage'] ?? 10);
724
        $maximumNumberOfLinks = (int)($paginateConfiguration['maximumNumberOfLinks'] ?? 10);
725
726
        $currentPage = $this->request->hasArgument('currentPage') ? (int)$this->request->getArgument('currentPage') : 1;
727
728
        $paginator = new QueryResultPaginator($queryResult, $currentPage, $itemsPerPage);
729
        if (class_exists(NumberedPagination::class)) {
730
            $pagination = new NumberedPagination($paginator, $maximumNumberOfLinks);
731
        } else {
732
            $pagination = new SimplePagination($paginator);
733
        }
734
735
        return [
736
            'paginator' => $paginator,
737
            'pagination' => $pagination,
738
        ];
739
    }
740
741
    /**
742
     * Get the allowed actions.
743
     *
744
     * @return array
745
     */
746
    protected function getAllowedActions(): array
747
    {
748
        $configuration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
749
        $allowedActions = [];
750
        foreach ($configuration['controllerConfiguration'] as $controllerName => $controllerActions) {
751
            $allowedActions[$controllerName] = $controllerActions['actions'];
752
        }
753
754
        return \is_array($allowedActions[__CLASS__]) ? $allowedActions[__CLASS__] : [];
755
    }
756
757
    /**
758
     * Get the current configurations.
759
     *
760
     * @return array
761
     */
762
    protected function getCurrentConfigurations()
763
    {
764
        $configurations = GeneralUtility::trimExplode(',', $this->settings['configuration'], true);
765
        $return = [];
766
        foreach (Register::getRegister() as $key => $configuration) {
767
            if (\in_array($key, $configurations, true)) {
768
                $return[] = $configuration;
769
            }
770
        }
771
772
        return $return;
773
    }
774
775
    /**
776
     * A redirect that have a slot included.
777
     *
778
     * @param string $signalClassName name of the signal class: __CLASS__
779
     * @param string $signalName      name of the signal: __FUNCTION__
780
     * @param array  $variables       optional: if not set use the defaults
781
     */
782
    protected function slottedRedirect($signalClassName, $signalName, $variables = null)
783
    {
784
        // set default variables for the redirect
785
        if (null === $variables) {
786
            $variables['extended'] = [
787
                'actionName' => 'list',
788
                'controllerName' => null,
789
                'extensionName' => null,
790
                'arguments' => [],
791
                'pageUid' => $this->settings['listPid'],
792
                'delay' => 0,
793
                'statusCode' => 301,
794
            ];
795
            $variables['extended']['pluginHmac'] = $this->calculatePluginHmac();
796
            $variables['settings'] = $this->settings;
797
        }
798
799
        $dispatcher = $this->objectManager->get(Dispatcher::class);
0 ignored issues
show
Deprecated Code introduced by
The method TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated with message: since TYPO3 10.4, will be removed in version 12.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
800
        $variables = $dispatcher->dispatch($signalClassName, $signalName, $variables);
801
802
        $this->redirect(
803
            $variables['extended']['actionName'],
804
            $variables['extended']['controllerName'],
805
            $variables['extended']['extensionName'],
806
            $variables['extended']['arguments'],
807
            $variables['extended']['pageUid'],
808
            $variables['extended']['delay'],
809
            $variables['extended']['statusCode']
810
        );
811
    }
812
}
813