Passed
Push — typo3_11 ( f34284...26342a )
by Torben
42:59
created

EventController   F

Complexity

Total Complexity 118

Size/Duplication

Total Lines 999
Duplicated Lines 0 %

Importance

Changes 10
Bugs 0 Features 0
Metric Value
eloc 504
dl 0
loc 999
rs 2
c 10
b 0
f 0
wmc 118

29 Methods

Rating   Name   Duplication   Size   Complexity  
A initializeView() 0 8 2
A initializeAction() 0 9 3
A injectEventCacheService() 0 3 1
A createEventDemandObjectFromSettings() 0 24 1
A createForeignRecordDemandObjectFromSettings() 0 10 1
A getCurrentLanguageTwoLetterIsoCode() 0 11 3
B handleEventNotFoundError() 0 29 7
A initializeSaveRegistrationAction() 0 11 1
B setRegistrationFieldValuesToArguments() 0 73 9
A icalDownloadAction() 0 10 5
A removePossibleSpamCheckFieldsFromArguments() 0 19 4
A evaluateSingleEventSetting() 0 7 3
B saveRegistrationResultAction() 0 57 11
A cancelRegistrationAction() 0 61 4
A checkPidOfEventRecord() 0 16 3
A registrationAction() 0 25 6
A persistAll() 0 3 1
A changeEventDemandToFullMonthDateRange() 0 23 1
B confirmRegistrationAction() 0 73 7
B searchAction() 0 44 7
A initializeSearchAction() 0 26 4
A listAction() 0 31 2
A isOverwriteDemand() 0 3 2
A detailAction() 0 19 6
A initializeListAction() 0 4 2
A evaluateIsShortcutSetting() 0 8 3
A getSysLanguageUid() 0 5 1
B calendarAction() 0 60 5
C saveRegistrationAction() 0 97 13

How to fix   Complexity   

Complex Class

Complex classes like EventController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EventController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
5
 *
6
 * For the full copyright and license information, please read the
7
 * LICENSE.txt file that was distributed with this source code.
8
 */
9
10
namespace DERHANSEN\SfEventMgt\Controller;
11
12
use DERHANSEN\SfEventMgt\Domain\Model\Dto\CategoryDemand;
13
use DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand;
14
use DERHANSEN\SfEventMgt\Domain\Model\Dto\ForeignRecordDemand;
15
use DERHANSEN\SfEventMgt\Domain\Model\Dto\SearchDemand;
16
use DERHANSEN\SfEventMgt\Domain\Model\Event;
17
use DERHANSEN\SfEventMgt\Domain\Model\Registration;
18
use DERHANSEN\SfEventMgt\Event\AfterRegistrationConfirmedEvent;
19
use DERHANSEN\SfEventMgt\Event\AfterRegistrationSavedEvent;
20
use DERHANSEN\SfEventMgt\Event\EventPidCheckFailedEvent;
21
use DERHANSEN\SfEventMgt\Event\ModifyCalendarViewVariablesEvent;
22
use DERHANSEN\SfEventMgt\Event\ModifyCancelRegistrationViewVariablesEvent;
23
use DERHANSEN\SfEventMgt\Event\ModifyConfirmRegistrationViewVariablesEvent;
24
use DERHANSEN\SfEventMgt\Event\ModifyCreateDependingRegistrationsEvent;
25
use DERHANSEN\SfEventMgt\Event\ModifyDetailViewVariablesEvent;
26
use DERHANSEN\SfEventMgt\Event\ModifyListViewVariablesEvent;
27
use DERHANSEN\SfEventMgt\Event\ModifyRegistrationViewVariablesEvent;
28
use DERHANSEN\SfEventMgt\Event\ModifySearchViewVariablesEvent;
29
use DERHANSEN\SfEventMgt\Event\WaitlistMoveUpEvent;
30
use DERHANSEN\SfEventMgt\Service\EventCacheService;
31
use DERHANSEN\SfEventMgt\Utility\MessageType;
32
use DERHANSEN\SfEventMgt\Utility\PageUtility;
33
use DERHANSEN\SfEventMgt\Utility\RegistrationResult;
34
use Psr\Http\Message\ServerRequestInterface;
35
use TYPO3\CMS\Core\Context\Context;
36
use TYPO3\CMS\Core\Http\ImmediateResponseException;
37
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
38
use TYPO3\CMS\Core\Utility\ArrayUtility;
39
use TYPO3\CMS\Core\Utility\GeneralUtility;
40
use TYPO3\CMS\Core\Utility\HttpUtility;
41
use TYPO3\CMS\Extbase\Annotation as Extbase;
42
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
43
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
44
use TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter;
45
use TYPO3\CMS\Fluid\View\StandaloneView;
46
use TYPO3\CMS\Frontend\Controller\ErrorController;
47
48
/**
49
 * EventController
50
 */
51
class EventController extends AbstractController
52
{
53
    /**
54
     * @var EventCacheService
55
     */
56
    protected $eventCacheService;
57
58
    /**
59
     * @param EventCacheService $cacheService
60
     */
61
    public function injectEventCacheService(EventCacheService $cacheService)
62
    {
63
        $this->eventCacheService = $cacheService;
64
    }
65
66
    /**
67
     * Assign contentObjectData and pageData to earch view
68
     *
69
     * @param \TYPO3\CMS\Extbase\Mvc\View\ViewInterface $view
70
     */
71
    protected function initializeView(\TYPO3\CMS\Extbase\Mvc\View\ViewInterface $view)
72
    {
73
        // @extensionScannerIgnoreLine
74
        $view->assign('contentObjectData', $this->configurationManager->getContentObject()->data);
75
        if (is_object($GLOBALS['TSFE'])) {
76
            $view->assign('pageData', $GLOBALS['TSFE']->page);
77
        }
78
        parent::initializeView($view);
79
    }
80
81
    /**
82
     * Initializes the current action
83
     */
84
    public function initializeAction()
85
    {
86
        $typoScriptFrontendController = $this->getTypoScriptFrontendController();
87
        if ($typoScriptFrontendController !== null) {
88
            static $cacheTagsSet = false;
89
90
            if (!$cacheTagsSet) {
91
                $typoScriptFrontendController->addCacheTags(['tx_sfeventmgt']);
92
                $cacheTagsSet = true;
93
            }
94
        }
95
    }
96
97
    /**
98
     * Creates an event demand object with the given settings
99
     *
100
     * @param array $settings The settings
101
     *
102
     * @return \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand
103
     */
104
    public function createEventDemandObjectFromSettings(array $settings): EventDemand
105
    {
106
        /** @var \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $demand */
107
        $demand = $this->objectManager->get(EventDemand::class);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated: since TYPO3 10.4, will be removed in version 12.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

107
        $demand = /** @scrutinizer ignore-deprecated */ $this->objectManager->get(EventDemand::class);

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

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

Loading history...
Deprecated Code introduced by
The property TYPO3\CMS\Extbase\Mvc\Co...troller::$objectManager has been deprecated: since v11, will be removed in v12 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

107
        $demand = /** @scrutinizer ignore-deprecated */ $this->objectManager->get(EventDemand::class);

This property 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 property will be removed from the class and what other property to use instead.

Loading history...
108
        $demand->setDisplayMode($settings['displayMode']);
109
        $demand->setStoragePage(
110
            PageUtility::extendPidListByChildren($settings['storagePage'] ?? '', $settings['recursive'] ?? 0)
111
        );
112
        $demand->setCategoryConjunction($settings['categoryConjunction']);
113
        $demand->setCategory($settings['category']);
114
        $demand->setIncludeSubcategories($settings['includeSubcategories']);
115
        $demand->setTopEventRestriction((int)$settings['topEventRestriction']);
116
        $demand->setOrderField($settings['orderField']);
117
        $demand->setOrderFieldAllowed($settings['orderFieldAllowed']);
118
        $demand->setOrderDirection($settings['orderDirection']);
119
        $demand->setQueryLimit($settings['queryLimit']);
120
        $demand->setLocation($settings['location']);
121
        $demand->setOrganisator($settings['organisator']);
122
        $demand->setSpeaker($settings['speaker']);
123
        $demand->setTimeRestrictionLow($settings['timeRestrictionLow']);
124
        $demand->setTimeRestrictionHigh($settings['timeRestrictionHigh']);
125
        $demand->setIncludeCurrent($settings['includeCurrent']);
126
127
        return $demand;
128
    }
129
130
    /**
131
     * Creates a foreign record demand object with the given settings
132
     *
133
     * @param array $settings The settings
134
     *
135
     * @return \DERHANSEN\SfEventMgt\Domain\Model\Dto\ForeignRecordDemand
136
     */
137
    public function createForeignRecordDemandObjectFromSettings(array $settings): ForeignRecordDemand
138
    {
139
        /** @var \DERHANSEN\SfEventMgt\Domain\Model\Dto\ForeignRecordDemand $demand */
140
        $demand = $this->objectManager->get(ForeignRecordDemand::class);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated: since TYPO3 10.4, will be removed in version 12.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

140
        $demand = /** @scrutinizer ignore-deprecated */ $this->objectManager->get(ForeignRecordDemand::class);

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

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

Loading history...
Deprecated Code introduced by
The property TYPO3\CMS\Extbase\Mvc\Co...troller::$objectManager has been deprecated: since v11, will be removed in v12 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

140
        $demand = /** @scrutinizer ignore-deprecated */ $this->objectManager->get(ForeignRecordDemand::class);

This property 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 property will be removed from the class and what other property to use instead.

Loading history...
141
        $demand->setStoragePage(
142
            PageUtility::extendPidListByChildren($settings['storagePage'] ?? '', $settings['recursive'] ?? 0)
143
        );
144
        $demand->setRestrictForeignRecordsToStoragePage((bool)$settings['restrictForeignRecordsToStoragePage']);
145
146
        return $demand;
147
    }
148
149
    /**
150
     * Initialize list action and set format
151
     */
152
    public function initializeListAction()
153
    {
154
        if (isset($this->settings['list']['format'])) {
155
            $this->request->setFormat($this->settings['list']['format']);
156
        }
157
    }
158
159
    /**
160
     * List view
161
     *
162
     * @param array $overwriteDemand OverwriteDemand
163
     */
164
    public function listAction(array $overwriteDemand = [])
165
    {
166
        $eventDemand = $this->createEventDemandObjectFromSettings($this->settings);
167
        $foreignRecordDemand = $this->createForeignRecordDemandObjectFromSettings($this->settings);
168
        $categoryDemand = CategoryDemand::createFromSettings($this->settings);
169
        if ($this->isOverwriteDemand($overwriteDemand)) {
170
            $eventDemand = $this->overwriteEventDemandObject($eventDemand, $overwriteDemand);
171
        }
172
        $events = $this->eventRepository->findDemanded($eventDemand);
173
        $categories = $this->categoryRepository->findDemanded($categoryDemand);
174
        $locations = $this->locationRepository->findDemanded($foreignRecordDemand);
175
        $organisators = $this->organisatorRepository->findDemanded($foreignRecordDemand);
176
        $speakers = $this->speakerRepository->findDemanded($foreignRecordDemand);
177
178
        $modifyListViewVariablesEvent = new ModifyListViewVariablesEvent(
179
            [
180
                'events' => $events,
181
                'categories' => $categories,
182
                'locations' => $locations,
183
                'organisators' => $organisators,
184
                'speakers' => $speakers,
185
                'overwriteDemand' => $overwriteDemand,
186
                'eventDemand' => $eventDemand
187
            ],
188
            $this
189
        );
190
        $this->eventDispatcher->dispatch($modifyListViewVariablesEvent);
191
        $variables = $modifyListViewVariablesEvent->getVariables();
192
        $this->view->assignMultiple($variables);
193
194
        $this->eventCacheService->addPageCacheTagsByEventDemandObject($eventDemand);
195
    }
196
197
    /**
198
     * Calendar view
199
     *
200
     * @param array $overwriteDemand OverwriteDemand
201
     */
202
    public function calendarAction(array $overwriteDemand = [])
203
    {
204
        $eventDemand = $this->createEventDemandObjectFromSettings($this->settings);
205
        $foreignRecordDemand = $this->createForeignRecordDemandObjectFromSettings($this->settings);
206
        $categoryDemand = CategoryDemand::createFromSettings($this->settings);
207
        if ($this->isOverwriteDemand($overwriteDemand)) {
208
            $eventDemand = $this->overwriteEventDemandObject($eventDemand, $overwriteDemand);
209
        }
210
211
        // Set month/year to demand if not given
212
        if (!$eventDemand->getMonth()) {
213
            $currentMonth = date('n');
214
            $eventDemand->setMonth($currentMonth);
0 ignored issues
show
Bug introduced by
$currentMonth of type string is incompatible with the type integer expected by parameter $month of DERHANSEN\SfEventMgt\Dom...EventDemand::setMonth(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

214
            $eventDemand->setMonth(/** @scrutinizer ignore-type */ $currentMonth);
Loading history...
215
        } else {
216
            $currentMonth = $eventDemand->getMonth();
217
        }
218
        if (!$eventDemand->getYear()) {
219
            $currentYear = date('Y');
220
            $eventDemand->setYear($currentYear);
0 ignored issues
show
Bug introduced by
$currentYear of type string is incompatible with the type integer expected by parameter $year of DERHANSEN\SfEventMgt\Dom...\EventDemand::setYear(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

220
            $eventDemand->setYear(/** @scrutinizer ignore-type */ $currentYear);
Loading history...
221
        } else {
222
            $currentYear = $eventDemand->getYear();
223
        }
224
225
        // Set demand from calendar date range instead of month / year
226
        if ((bool)$this->settings['calendar']['includeEventsForEveryDayOfAllCalendarWeeks']) {
227
            $eventDemand = $this->changeEventDemandToFullMonthDateRange($eventDemand);
228
        }
229
230
        $events = $this->eventRepository->findDemanded($eventDemand);
231
        $weeks = $this->calendarService->getCalendarArray(
232
            $currentMonth,
0 ignored issues
show
Bug introduced by
It seems like $currentMonth can also be of type string; however, parameter $month of DERHANSEN\SfEventMgt\Ser...ice::getCalendarArray() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

232
            /** @scrutinizer ignore-type */ $currentMonth,
Loading history...
233
            $currentYear,
0 ignored issues
show
Bug introduced by
It seems like $currentYear can also be of type string; however, parameter $year of DERHANSEN\SfEventMgt\Ser...ice::getCalendarArray() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

233
            /** @scrutinizer ignore-type */ $currentYear,
Loading history...
234
            strtotime('today midnight'),
235
            (int)$this->settings['calendar']['firstDayOfWeek'],
236
            $events
237
        );
238
239
        $modifyCalendarViewVariablesEvent = new ModifyCalendarViewVariablesEvent(
240
            [
241
                'events' => $events,
242
                'weeks' => $weeks,
243
                'categories' => $this->categoryRepository->findDemanded($categoryDemand),
244
                'locations' => $this->locationRepository->findDemanded($foreignRecordDemand),
245
                'organisators' => $this->organisatorRepository->findDemanded($foreignRecordDemand),
246
                'eventDemand' => $eventDemand,
247
                'overwriteDemand' => $overwriteDemand,
248
                'currentPageId' => $GLOBALS['TSFE']->id,
249
                'firstDayOfMonth' => \DateTime::createFromFormat(
250
                    'd.m.Y',
251
                    sprintf('1.%s.%s', $currentMonth, $currentYear)
252
                ),
253
                'previousMonthConfig' => $this->calendarService->getDateConfig($currentMonth, $currentYear, '-1 month'),
0 ignored issues
show
Bug introduced by
It seems like $currentMonth can also be of type string; however, parameter $month of DERHANSEN\SfEventMgt\Ser...ervice::getDateConfig() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

253
                'previousMonthConfig' => $this->calendarService->getDateConfig(/** @scrutinizer ignore-type */ $currentMonth, $currentYear, '-1 month'),
Loading history...
Bug introduced by
It seems like $currentYear can also be of type string; however, parameter $year of DERHANSEN\SfEventMgt\Ser...ervice::getDateConfig() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

253
                'previousMonthConfig' => $this->calendarService->getDateConfig($currentMonth, /** @scrutinizer ignore-type */ $currentYear, '-1 month'),
Loading history...
254
                'nextMonthConfig' => $this->calendarService->getDateConfig($currentMonth, $currentYear, '+1 month')
255
            ],
256
            $this
257
        );
258
        $this->eventDispatcher->dispatch($modifyCalendarViewVariablesEvent);
259
        $variables = $modifyCalendarViewVariablesEvent->getVariables();
260
261
        $this->view->assignMultiple($variables);
262
    }
263
264
    /**
265
     * Changes the given event demand object to select a date range for a calendar month including days of the previous
266
     * month for the first week and they days for the next month for the last week
267
     *
268
     * @param EventDemand $eventDemand
269
     * @return EventDemand
270
     */
271
    protected function changeEventDemandToFullMonthDateRange(EventDemand $eventDemand)
272
    {
273
        $calendarDateRange = $this->calendarService->getCalendarDateRange(
274
            $eventDemand->getMonth(),
275
            $eventDemand->getYear(),
276
            $this->settings['calendar']['firstDayOfWeek']
277
        );
278
279
        $eventDemand->setMonth(0);
280
        $eventDemand->setYear(0);
281
282
        $startDate = new \DateTime();
283
        $startDate->setTimestamp($calendarDateRange['firstDayOfCalendar']);
284
        $endDate = new \DateTime();
285
        $endDate->setTimestamp($calendarDateRange['lastDayOfCalendar']);
286
        $endDate->setTime(23, 59, 59);
287
288
        $searchDemand = new SearchDemand();
289
        $searchDemand->setStartDate($startDate);
290
        $searchDemand->setEndDate($endDate);
291
        $eventDemand->setSearchDemand($searchDemand);
292
293
        return $eventDemand;
294
    }
295
296
    /**
297
     * Detail view for an event
298
     *
299
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
300
     * @return mixed string|void
301
     */
302
    public function detailAction(Event $event = null)
303
    {
304
        $event = $this->evaluateSingleEventSetting($event);
305
        $event = $this->evaluateIsShortcutSetting($event);
306
        if (is_a($event, Event::class) && $this->settings['detail']['checkPidOfEventRecord']) {
307
            $event = $this->checkPidOfEventRecord($event);
308
        }
309
310
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
311
            return $this->handleEventNotFoundError($this->settings);
312
        }
313
314
        $modifyDetailViewVariablesEvent = new ModifyDetailViewVariablesEvent(['event' => $event], $this);
315
        $this->eventDispatcher->dispatch($modifyDetailViewVariablesEvent);
316
        $variables = $modifyDetailViewVariablesEvent->getVariables();
317
318
        $this->view->assignMultiple($variables);
319
        if ($event !== null) {
320
            $this->eventCacheService->addCacheTagsByEventRecords([$event]);
321
        }
322
    }
323
324
    /**
325
     * Error handling if event is not found
326
     *
327
     * @param array $settings
328
     */
329
    protected function handleEventNotFoundError($settings)
330
    {
331
        if (empty($settings['event']['errorHandling'])) {
332
            return null;
333
        }
334
335
        $configuration = GeneralUtility::trimExplode(',', $settings['event']['errorHandling'], true);
336
337
        switch ($configuration[0]) {
338
            case 'redirectToListView':
339
                $listPid = (int)$settings['listPid'] > 0 ? (int)$settings['listPid'] : 1;
340
                $this->redirect('list', null, null, null, $listPid);
341
                break;
342
            case 'pageNotFoundHandler':
343
                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
344
                    $GLOBALS['TYPO3_REQUEST'],
345
                    'Event not found.'
346
                );
347
                throw new ImmediateResponseException($response, 1549896549);
348
            case 'showStandaloneTemplate':
349
                if (isset($configuration[2])) {
350
                    $statusCode = constant(HttpUtility::class . '::HTTP_STATUS_' . $configuration[2]);
351
                    HttpUtility::setResponseCode($statusCode);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Core\Utility\H...lity::setResponseCode() has been deprecated: since v11, will be removed in v12. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

351
                    /** @scrutinizer ignore-deprecated */ HttpUtility::setResponseCode($statusCode);

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

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

Loading history...
352
                }
353
                $standaloneTemplate = GeneralUtility::makeInstance(StandaloneView::class);
354
                $standaloneTemplate->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($configuration[1]));
355
356
                return $standaloneTemplate->render();
357
            default:
358
        }
359
    }
360
361
    /**
362
     * Initiates the iCalendar download for the given event
363
     *
364
     * @param Event $event The event
365
     *
366
     * @return string|false
367
     */
368
    public function icalDownloadAction(Event $event = null)
369
    {
370
        if (is_a($event, Event::class) && $this->settings['detail']['checkPidOfEventRecord']) {
371
            $event = $this->checkPidOfEventRecord($event);
372
        }
373
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
374
            return $this->handleEventNotFoundError($this->settings);
375
        }
376
        $this->icalendarService->downloadiCalendarFile($event);
0 ignored issues
show
Bug introduced by
It seems like $event can also be of type null; however, parameter $event of DERHANSEN\SfEventMgt\Ser...downloadiCalendarFile() does only seem to accept DERHANSEN\SfEventMgt\Domain\Model\Event, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

376
        $this->icalendarService->downloadiCalendarFile(/** @scrutinizer ignore-type */ $event);
Loading history...
377
        exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
378
    }
379
380
    /**
381
     * Registration view for an event
382
     *
383
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
384
     *
385
     * @return mixed string|void
386
     */
387
    public function registrationAction(Event $event = null)
388
    {
389
        $event = $this->evaluateSingleEventSetting($event);
390
        if (is_a($event, Event::class) && $this->settings['registration']['checkPidOfEventRecord']) {
391
            $event = $this->checkPidOfEventRecord($event);
392
        }
393
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
394
            return $this->handleEventNotFoundError($this->settings);
395
        }
396
        if ($event->getRestrictPaymentMethods()) {
397
            $paymentMethods = $this->paymentService->getRestrictedPaymentMethods($event);
398
        } else {
399
            $paymentMethods = $this->paymentService->getPaymentMethods();
400
        }
401
402
        $modifyRegistrationViewVariablesEvent = new ModifyRegistrationViewVariablesEvent(
403
            [
404
                'event' => $event,
405
                'paymentMethods' => $paymentMethods,
406
            ],
407
            $this
408
        );
409
        $this->eventDispatcher->dispatch($modifyRegistrationViewVariablesEvent);
410
        $variables = $modifyRegistrationViewVariablesEvent->getVariables();
411
        $this->view->assignMultiple($variables);
412
    }
413
414
    /**
415
     * Removes all possible spamcheck fields (which do not belong to the domain model) from arguments.
416
     */
417
    protected function removePossibleSpamCheckFieldsFromArguments()
418
    {
419
        $arguments = $this->request->getArguments();
420
        if (!isset($arguments['event'])) {
421
            return;
422
        }
423
424
        // Remove a possible honeypot field
425
        $honeypotField = 'hp' . (int)$arguments['event'];
426
        if (isset($arguments['registration'][$honeypotField])) {
427
            unset($arguments['registration'][$honeypotField]);
428
        }
429
430
        // Remove a possible challenge/response field
431
        if (isset($arguments['registration']['cr-response'])) {
432
            unset($arguments['registration']['cr-response']);
433
        }
434
435
        $this->request->setArguments($arguments);
436
    }
437
438
    /**
439
     * Processes incoming registrations fields and adds field values to arguments
440
     */
441
    protected function setRegistrationFieldValuesToArguments()
442
    {
443
        $arguments = $this->request->getArguments();
444
        if (!isset($arguments['event'])) {
445
            return;
446
        }
447
448
        /** @var Event $event */
449
        $event = $this->eventRepository->findByUid((int)$this->request->getArgument('event'));
450
        if (!$event || $event->getRegistrationFields()->count() === 0) {
0 ignored issues
show
introduced by
$event is of type DERHANSEN\SfEventMgt\Domain\Model\Event, thus it always evaluated to true.
Loading history...
451
            return;
452
        }
453
454
        $registrationMvcArgument = $this->arguments->getArgument('registration');
455
        $propertyMapping = $registrationMvcArgument->getPropertyMappingConfiguration();
456
        $propertyMapping->allowProperties('fieldValues');
457
        $propertyMapping->allowCreationForSubProperty('fieldValues');
458
        $propertyMapping->allowModificationForSubProperty('fieldValues');
459
460
        // allow creation of new objects (for validation)
461
        $propertyMapping->setTypeConverterOptions(
462
            PersistentObjectConverter::class,
463
            [
464
                PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED => true,
465
                PersistentObjectConverter::CONFIGURATION_MODIFICATION_ALLOWED => true
466
            ]
467
        );
468
469
        // Set event to registration (required for validation)
470
        $propertyMapping->allowProperties('event');
471
        $propertyMapping->allowCreationForSubProperty('event');
472
        $propertyMapping->allowModificationForSubProperty('event');
473
        $arguments['registration']['event'] = (int)$this->request->getArgument('event');
474
475
        $index = 0;
476
        foreach ((array)$arguments['registration']['fields'] as $fieldUid => $value) {
477
            // Only accept registration fields of the current event
478
            if (!in_array((int)$fieldUid, $event->getRegistrationFieldsUids(), true)) {
479
                continue;
480
            }
481
482
            // allow subvalues in new property mapper
483
            $propertyMapping->forProperty('fieldValues')->allowProperties($index);
484
            $propertyMapping->forProperty('fieldValues.' . $index)->allowAllProperties();
485
            $propertyMapping->allowCreationForSubProperty('fieldValues.' . $index);
486
            $propertyMapping->allowModificationForSubProperty('fieldValues.' . $index);
487
488
            if (is_array($value)) {
489
                if (empty($value)) {
490
                    $value = '';
491
                } else {
492
                    $value = json_encode($value);
493
                }
494
            }
495
496
            /** @var Registration\Field $field */
497
            $field = $this->fieldRepository->findByUid((int)$fieldUid);
498
499
            $arguments['registration']['fieldValues'][$index] = [
500
                'pid' => $field->getPid(),
501
                'value' => $value,
502
                'field' => (string)$fieldUid,
503
                'valueType' => $field->getValueType()
504
            ];
505
506
            $index++;
507
        }
508
509
        // Remove temporary "fields" field
510
        if (isset($arguments['registration']['fields'])) {
511
            $arguments = ArrayUtility::removeByPath($arguments, 'registration/fields');
512
        }
513
        $this->request->setArguments($arguments);
514
    }
515
516
    /**
517
     * Set date format for field dateOfBirth
518
     */
519
    public function initializeSaveRegistrationAction()
520
    {
521
        $this->arguments->getArgument('registration')
522
            ->getPropertyMappingConfiguration()->forProperty('dateOfBirth')
523
            ->setTypeConverterOption(
524
                DateTimeConverter::class,
525
                DateTimeConverter::CONFIGURATION_DATE_FORMAT,
526
                $this->settings['registration']['formatDateOfBirth']
527
            );
528
        $this->removePossibleSpamCheckFieldsFromArguments();
529
        $this->setRegistrationFieldValuesToArguments();
530
    }
531
532
    /**
533
     * Saves the registration
534
     *
535
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
536
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
537
     * @Extbase\Validate("DERHANSEN\SfEventMgt\Validation\Validator\RegistrationFieldValidator", param="registration")
538
     * @Extbase\Validate("DERHANSEN\SfEventMgt\Validation\Validator\RegistrationValidator", param="registration")
539
     *
540
     * @return mixed string|void
541
     */
542
    public function saveRegistrationAction(Registration $registration, Event $event)
543
    {
544
        if (is_a($event, Event::class) && $this->settings['registration']['checkPidOfEventRecord']) {
545
            $event = $this->checkPidOfEventRecord($event);
546
        }
547
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
548
            return $this->handleEventNotFoundError($this->settings);
549
        }
550
        $autoConfirmation = (bool)$this->settings['registration']['autoConfirmation'] || $event->getEnableAutoconfirm();
551
        $result = RegistrationResult::REGISTRATION_SUCCESSFUL;
552
        list($success, $result) = $this->registrationService->checkRegistrationSuccess($event, $registration, $result);
553
554
        // Save registration if no errors
555
        if ($success) {
556
            $isWaitlistRegistration = $this->registrationService->isWaitlistRegistration(
557
                $event,
558
                $registration->getAmountOfRegistrations()
559
            );
560
            $linkValidity = (int)$this->settings['confirmation']['linkValidity'];
561
            if ($linkValidity === 0) {
562
                // Use 3600 seconds as default value if not set
563
                $linkValidity = 3600;
564
            }
565
            $confirmationUntil = new \DateTime();
566
            $confirmationUntil->add(new \DateInterval('PT' . $linkValidity . 'S'));
567
568
            $registration->setEvent($event);
569
            $registration->setPid($event->getPid());
570
            $registration->setRegistrationDate(new \DateTime());
571
            $registration->setConfirmationUntil($confirmationUntil);
572
            $registration->setLanguage($this->getCurrentLanguageTwoLetterIsoCode());
573
            $registration->setFeUser($this->registrationService->getCurrentFeUserObject());
574
            $registration->setWaitlist($isWaitlistRegistration);
575
            $this->registrationRepository->add($registration);
576
577
            // Persist registration, so we have an UID
578
            $this->persistAll();
579
580
            if ($isWaitlistRegistration) {
581
                $messageType = MessageType::REGISTRATION_WAITLIST_NEW;
582
            } else {
583
                $messageType = MessageType::REGISTRATION_NEW;
584
            }
585
586
            $this->eventDispatcher->dispatch(new AfterRegistrationSavedEvent($registration, $this));
587
588
            // Send notifications to user and admin if confirmation link should be sent
589
            if (!$autoConfirmation) {
590
                $this->notificationService->sendUserMessage(
591
                    $event,
592
                    $registration,
593
                    $this->settings,
594
                    $messageType
595
                );
596
                $this->notificationService->sendAdminMessage(
597
                    $event,
598
                    $registration,
599
                    $this->settings,
600
                    $messageType
601
                );
602
            }
603
604
            // Create given amount of registrations if necessary
605
            $modifyCreateDependingRegistrationsEvent = new ModifyCreateDependingRegistrationsEvent(
606
                $registration,
607
                ($registration->getAmountOfRegistrations() > 1),
608
                $this
609
            );
610
            $this->eventDispatcher->dispatch($modifyCreateDependingRegistrationsEvent);
611
            $createDependingRegistrations = $modifyCreateDependingRegistrationsEvent->getCreateDependingRegistrations();
612
            if ($createDependingRegistrations) {
613
                $this->registrationService->createDependingRegistrations($registration);
614
            }
615
616
            // Flush page cache for event, since new registration has been added
617
            $this->eventCacheService->flushEventCache($event->getUid(), $event->getPid());
618
        }
619
620
        if ($autoConfirmation && $success) {
621
            $this->redirect(
622
                'confirmRegistration',
623
                null,
624
                null,
625
                [
626
                    'reguid' => $registration->getUid(),
627
                    'hmac' => $this->hashService->generateHmac('reg-' . $registration->getUid())
628
                ]
629
            );
630
        } else {
631
            $this->redirect(
632
                'saveRegistrationResult',
633
                null,
634
                null,
635
                [
636
                    'result' => $result,
637
                    'eventuid' => $event->getUid(),
638
                    'hmac' => $this->hashService->generateHmac('event-' . $event->getUid())
639
                ]
640
            );
641
        }
642
    }
643
644
    /**
645
     * Shows the result of the saveRegistrationAction
646
     *
647
     * @param int $result Result
648
     * @param int $eventuid
649
     * @param string $hmac
650
     */
651
    public function saveRegistrationResultAction($result, $eventuid, $hmac)
652
    {
653
        $event = null;
654
655
        switch ($result) {
656
            case RegistrationResult::REGISTRATION_SUCCESSFUL:
657
                $messageKey = 'event.message.registrationsuccessful';
658
                $titleKey = 'registrationResult.title.successful';
659
                break;
660
            case RegistrationResult::REGISTRATION_SUCCESSFUL_WAITLIST:
661
                $messageKey = 'event.message.registrationwaitlistsuccessful';
662
                $titleKey = 'registrationWaitlistResult.title.successful';
663
                break;
664
            case RegistrationResult::REGISTRATION_FAILED_EVENT_EXPIRED:
665
                $messageKey = 'event.message.registrationfailedeventexpired';
666
                $titleKey = 'registrationResult.title.failed';
667
                break;
668
            case RegistrationResult::REGISTRATION_FAILED_MAX_PARTICIPANTS:
669
                $messageKey = 'event.message.registrationfailedmaxparticipants';
670
                $titleKey = 'registrationResult.title.failed';
671
                break;
672
            case RegistrationResult::REGISTRATION_NOT_ENABLED:
673
                $messageKey = 'event.message.registrationfailednotenabled';
674
                $titleKey = 'registrationResult.title.failed';
675
                break;
676
            case RegistrationResult::REGISTRATION_FAILED_DEADLINE_EXPIRED:
677
                $messageKey = 'event.message.registrationfaileddeadlineexpired';
678
                $titleKey = 'registrationResult.title.failed';
679
                break;
680
            case RegistrationResult::REGISTRATION_FAILED_NOT_ENOUGH_FREE_PLACES:
681
                $messageKey = 'event.message.registrationfailednotenoughfreeplaces';
682
                $titleKey = 'registrationResult.title.failed';
683
                break;
684
            case RegistrationResult::REGISTRATION_FAILED_MAX_AMOUNT_REGISTRATIONS_EXCEEDED:
685
                $messageKey = 'event.message.registrationfailedmaxamountregistrationsexceeded';
686
                $titleKey = 'registrationResult.title.failed';
687
                break;
688
            case RegistrationResult::REGISTRATION_FAILED_EMAIL_NOT_UNIQUE:
689
                $messageKey = 'event.message.registrationfailedemailnotunique';
690
                $titleKey = 'registrationResult.title.failed';
691
                break;
692
            default:
693
                $messageKey = '';
694
                $titleKey = '';
695
        }
696
697
        if (!$this->hashService->validateHmac('event-' . $eventuid, $hmac)) {
698
            $messageKey = 'event.message.registrationsuccessfulwrongeventhmac';
699
            $titleKey = 'registrationResult.title.failed';
700
        } else {
701
            $event = $this->eventRepository->findByUid((int)$eventuid);
702
        }
703
704
        $this->view->assignMultiple([
705
            'messageKey' => $messageKey,
706
            'titleKey' => $titleKey,
707
            'event' => $event,
708
        ]);
709
    }
710
711
    /**
712
     * Confirms the registration if possible and sends emails to admin and user
713
     *
714
     * @param int $reguid UID of registration
715
     * @param string $hmac HMAC for parameters
716
     */
717
    public function confirmRegistrationAction($reguid, $hmac)
718
    {
719
        $event = null;
720
721
        /* @var $registration Registration */
722
        list($failed, $registration, $messageKey, $titleKey) = $this->registrationService->checkConfirmRegistration(
723
            $reguid,
724
            $hmac
725
        );
726
727
        if ($failed === false) {
728
            $registration->setConfirmed(true);
729
            $event = $registration->getEvent();
730
            $this->registrationRepository->update($registration);
731
732
            $this->eventDispatcher->dispatch(new AfterRegistrationConfirmedEvent($registration, $this));
733
734
            $messageType = MessageType::REGISTRATION_CONFIRMED;
735
            if ($registration->getWaitlist()) {
736
                $messageType = MessageType::REGISTRATION_WAITLIST_CONFIRMED;
737
            }
738
739
            // Send notifications to user and admin
740
            $this->notificationService->sendUserMessage(
741
                $registration->getEvent(),
742
                $registration,
743
                $this->settings,
744
                $messageType
745
            );
746
            $this->notificationService->sendAdminMessage(
747
                $registration->getEvent(),
748
                $registration,
749
                $this->settings,
750
                $messageType
751
            );
752
753
            // Confirm registrations depending on main registration if necessary
754
            if ($registration->getAmountOfRegistrations() > 1) {
755
                $this->registrationService->confirmDependingRegistrations($registration);
756
            }
757
        }
758
759
        // Redirect to payment provider if payment/redirect is enabled
760
        $paymentPid = (int)$this->settings['paymentPid'];
761
        if (!$failed && $paymentPid > 0 && $this->registrationService->redirectPaymentEnabled($registration)) {
762
            $this->uriBuilder->reset()
763
                ->setTargetPageUid($paymentPid);
764
            $uri = $this->uriBuilder->uriFor(
765
                'redirect',
766
                [
767
                    'registration' => $registration,
768
                    'hmac' => $this->hashService->generateHmac('redirectAction-' . $registration->getUid())
769
                ],
770
                'Payment',
771
                'sfeventmgt',
772
                'Pipayment'
773
            );
774
            $this->redirectToUri($uri);
775
        }
776
777
        $modifyConfirmRegistrationViewVariablesEvent = new ModifyConfirmRegistrationViewVariablesEvent(
778
            [
779
                'failed' => $failed,
780
                'messageKey' => $messageKey,
781
                'titleKey' => $titleKey,
782
                'event' => $event,
783
                'registration' => $registration,
784
            ],
785
            $this
786
        );
787
        $this->eventDispatcher->dispatch($modifyConfirmRegistrationViewVariablesEvent);
788
        $variables = $modifyConfirmRegistrationViewVariablesEvent->getVariables();
789
        $this->view->assignMultiple($variables);
790
    }
791
792
    /**
793
     * Cancels the registration if possible and sends emails to admin and user
794
     *
795
     * @param int $reguid UID of registration
796
     * @param string $hmac HMAC for parameters
797
     */
798
    public function cancelRegistrationAction($reguid, $hmac)
799
    {
800
        $event = null;
801
802
        /* @var $registration Registration */
803
        list($failed, $registration, $messageKey, $titleKey) =
804
            $this->registrationService->checkCancelRegistration($reguid, $hmac);
805
806
        if ($failed === false) {
807
            $event = $registration->getEvent();
808
809
            // Send notifications (must run before cancelling the registration)
810
            $this->notificationService->sendUserMessage(
811
                $registration->getEvent(),
812
                $registration,
813
                $this->settings,
814
                MessageType::REGISTRATION_CANCELLED
815
            );
816
            $this->notificationService->sendAdminMessage(
817
                $registration->getEvent(),
818
                $registration,
819
                $this->settings,
820
                MessageType::REGISTRATION_CANCELLED
821
            );
822
823
            // First cancel depending registrations
824
            if ($registration->getAmountOfRegistrations() > 1) {
825
                $this->registrationService->cancelDependingRegistrations($registration);
826
            }
827
828
            // Finally cancel registration
829
            $this->registrationRepository->remove($registration);
830
831
            // Persist changes, so following functions can work with $event properties (e.g. amount of registrations)
832
            $this->persistAll();
833
834
            // Dispatch event, so waitlist registrations can be moved up and default move up process can be stopped
835
            $waitlistMoveUpEvent = new WaitlistMoveUpEvent($event, $this, true);
836
            $this->eventDispatcher->dispatch($waitlistMoveUpEvent);
837
838
            // Move up waitlist registrations if configured on event basis and if not disabled by $waitlistMoveUpEvent
839
            if ($waitlistMoveUpEvent->getProcessDefaultMoveUp()) {
840
                $this->registrationService->moveUpWaitlistRegistrations($event, $this->settings);
841
            }
842
843
            // Flush page cache for event, since amount of registrations has changed
844
            $this->eventCacheService->flushEventCache($event->getUid(), $event->getPid());
0 ignored issues
show
Bug introduced by
It seems like $event->getPid() can also be of type null; however, parameter $eventPid of DERHANSEN\SfEventMgt\Ser...vice::flushEventCache() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

844
            $this->eventCacheService->flushEventCache($event->getUid(), /** @scrutinizer ignore-type */ $event->getPid());
Loading history...
Bug introduced by
It seems like $event->getUid() can also be of type null; however, parameter $eventUid of DERHANSEN\SfEventMgt\Ser...vice::flushEventCache() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

844
            $this->eventCacheService->flushEventCache(/** @scrutinizer ignore-type */ $event->getUid(), $event->getPid());
Loading history...
845
        }
846
847
        $modifyCancelRegistrationViewVariablesEvent = new ModifyCancelRegistrationViewVariablesEvent(
848
            [
849
                'failed' => $failed,
850
                'messageKey' => $messageKey,
851
                'titleKey' => $titleKey,
852
                'event' => $event,
853
            ],
854
            $this
855
        );
856
        $this->eventDispatcher->dispatch($modifyCancelRegistrationViewVariablesEvent);
857
        $variables = $modifyCancelRegistrationViewVariablesEvent->getVariables();
858
        $this->view->assignMultiple($variables);
859
    }
860
861
    /**
862
     * Set date format for field startDate and endDate
863
     */
864
    public function initializeSearchAction()
865
    {
866
        if ($this->settings !== null && $this->settings['search']['dateFormat']) {
867
            $this->arguments->getArgument('searchDemand')
868
                ->getPropertyMappingConfiguration()->forProperty('startDate')
869
                ->setTypeConverterOption(
870
                    DateTimeConverter::class,
871
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
872
                    $this->settings['search']['dateFormat']
873
                );
874
            $this->arguments->getArgument('searchDemand')
875
                ->getPropertyMappingConfiguration()->forProperty('endDate')
876
                ->setTypeConverterOption(
877
                    DateTimeConverter::class,
878
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
879
                    $this->settings['search']['dateFormat']
880
                );
881
        }
882
        if ($this->arguments->hasArgument('searchDemand')) {
883
            $propertyMappingConfiguration = $this->arguments->getArgument('searchDemand')
884
                ->getPropertyMappingConfiguration();
885
            $propertyMappingConfiguration->allowAllProperties();
886
            $propertyMappingConfiguration->setTypeConverterOption(
887
                PersistentObjectConverter::class,
888
                PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED,
889
                true
890
            );
891
        }
892
    }
893
894
    /**
895
     * Search view
896
     *
897
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\SearchDemand $searchDemand SearchDemand
898
     * @param array $overwriteDemand OverwriteDemand
899
     */
900
    public function searchAction(SearchDemand $searchDemand = null, array $overwriteDemand = [])
901
    {
902
        $eventDemand = $this->createEventDemandObjectFromSettings($this->settings);
903
        $eventDemand->setSearchDemand($searchDemand);
904
        $foreignRecordDemand = $this->createForeignRecordDemandObjectFromSettings($this->settings);
905
        $categoryDemand = CategoryDemand::createFromSettings($this->settings);
906
907
        if ($searchDemand !== null) {
908
            $searchDemand->setFields($this->settings['search']['fields']);
909
910
            if ($this->settings['search']['adjustTime'] && $searchDemand->getStartDate() !== null) {
911
                $searchDemand->getStartDate()->setTime(0, 0, 0);
912
            }
913
914
            if ($this->settings['search']['adjustTime'] && $searchDemand->getEndDate() !== null) {
915
                $searchDemand->getEndDate()->setTime(23, 59, 59);
916
            }
917
        }
918
919
        if ($this->isOverwriteDemand($overwriteDemand)) {
920
            $eventDemand = $this->overwriteEventDemandObject($eventDemand, $overwriteDemand);
921
        }
922
923
        $categories = $this->categoryRepository->findDemanded($categoryDemand);
924
        $locations = $this->locationRepository->findDemanded($foreignRecordDemand);
925
        $organisators = $this->organisatorRepository->findDemanded($foreignRecordDemand);
926
        $speakers = $this->speakerRepository->findDemanded($foreignRecordDemand);
927
        $events = $this->eventRepository->findDemanded($eventDemand);
928
929
        $modifySearchViewVariablesEvent = new ModifySearchViewVariablesEvent(
930
            [
931
                'events' => $events,
932
                'categories' => $categories,
933
                'locations' => $locations,
934
                'organisators' => $organisators,
935
                'speakers' => $speakers,
936
                'searchDemand' => $searchDemand,
937
                'overwriteDemand' => $overwriteDemand,
938
            ],
939
            $this
940
        );
941
        $this->eventDispatcher->dispatch($modifySearchViewVariablesEvent);
942
        $variables = $modifySearchViewVariablesEvent->getVariables();
943
        $this->view->assignMultiple($variables);
944
    }
945
946
    /**
947
     * Returns if a demand object can be overwritten with the given overwriteDemand array
948
     *
949
     * @param array $overwriteDemand
950
     * @return bool
951
     */
952
    protected function isOverwriteDemand($overwriteDemand)
953
    {
954
        return $this->settings['disableOverrideDemand'] != 1 && $overwriteDemand !== [];
955
    }
956
957
    /**
958
     * If no event is given and the singleEvent setting is set, the configured single event is returned
959
     *
960
     * @param Event|null $event
961
     * @return Event|null
962
     */
963
    protected function evaluateSingleEventSetting($event)
964
    {
965
        if ($event === null && (int)$this->settings['singleEvent'] > 0) {
966
            $event = $this->eventRepository->findByUid((int)$this->settings['singleEvent']);
967
        }
968
969
        return $event;
970
    }
971
972
    /**
973
     * If no event is given and the isShortcut setting is set, the event is displayed using the "Insert Record"
974
     * content element and should be loaded from contect object data
975
     *
976
     * @param Event|null $event
977
     * @return Event|null
978
     */
979
    protected function evaluateIsShortcutSetting($event)
980
    {
981
        if ($event === null && (bool)$this->settings['detail']['isShortcut']) {
982
            $eventRawData = $this->configurationManager->getContentObject()->data;
983
            $event = $this->eventRepository->findByUid($eventRawData['uid']);
984
        }
985
986
        return $event;
987
    }
988
989
    /**
990
     * Checks if the event pid could be found in the storagePage settings of the detail plugin and
991
     * if the pid could not be found it return null instead of the event object.
992
     *
993
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
994
     * @return \DERHANSEN\SfEventMgt\Domain\Model\Event|null
995
     */
996
    protected function checkPidOfEventRecord(Event $event): ?Event
997
    {
998
        $allowedStoragePages = GeneralUtility::trimExplode(
999
            ',',
1000
            PageUtility::extendPidListByChildren(
1001
                $this->settings['storagePage'] ?? '',
1002
                $this->settings['recursive'] ?? 0
1003
            ),
1004
            true
1005
        );
1006
        if (count($allowedStoragePages) > 0 && !in_array($event->getPid(), $allowedStoragePages)) {
1007
            $this->eventDispatcher->dispatch(new EventPidCheckFailedEvent($event, $this));
1008
            $event = null;
1009
        }
1010
1011
        return $event;
1012
    }
1013
1014
    /**
1015
     * Calls persistAll() of the persistenceManager
1016
     */
1017
    protected function persistAll()
1018
    {
1019
        $this->objectManager->get(PersistenceManager::class)->persistAll();
0 ignored issues
show
Deprecated Code introduced by
The property TYPO3\CMS\Extbase\Mvc\Co...troller::$objectManager has been deprecated: since v11, will be removed in v12 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1019
        /** @scrutinizer ignore-deprecated */ $this->objectManager->get(PersistenceManager::class)->persistAll();

This property 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 property will be removed from the class and what other property to use instead.

Loading history...
Deprecated Code introduced by
The function TYPO3\CMS\Extbase\Object...ManagerInterface::get() has been deprecated: since TYPO3 10.4, will be removed in version 12.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1019
        /** @scrutinizer ignore-deprecated */ $this->objectManager->get(PersistenceManager::class)->persistAll();

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

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

Loading history...
1020
    }
1021
1022
    /**
1023
     * Returns the current sys_language_uid
1024
     *
1025
     * @return int
1026
     */
1027
    protected function getSysLanguageUid(): int
1028
    {
1029
        $languageAspect = GeneralUtility::makeInstance(Context::class)->getAspect('language');
1030
1031
        return $languageAspect->getId();
1032
    }
1033
1034
    /**
1035
     * Returns the two letter ISO code for the current language
1036
     *
1037
     * @return string
1038
     */
1039
    protected function getCurrentLanguageTwoLetterIsoCode(): string
1040
    {
1041
        if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface &&
1042
            $GLOBALS['TYPO3_REQUEST']->getAttribute('language') instanceof SiteLanguage
1043
        ) {
1044
            /** @var SiteLanguage $siteLanguage */
1045
            $siteLanguage = $GLOBALS['TYPO3_REQUEST']->getAttribute('language');
1046
            return $siteLanguage->getTwoLetterIsoCode();
1047
        }
1048
1049
        return '';
1050
    }
1051
}
1052