Completed
Push — development ( c1e1bc...13d7a7 )
by Torben
01:23
created

EventController::injectEventCacheService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
namespace DERHANSEN\SfEventMgt\Controller;
3
4
/*
5
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
6
 *
7
 * For the full copyright and license information, please read the
8
 * LICENSE.txt file that was distributed with this source code.
9
 */
10
11
use DERHANSEN\SfEventMgt\Domain\Model\Dto\CategoryDemand;
12
use DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand;
13
use DERHANSEN\SfEventMgt\Domain\Model\Dto\ForeignRecordDemand;
14
use DERHANSEN\SfEventMgt\Domain\Model\Dto\SearchDemand;
15
use DERHANSEN\SfEventMgt\Domain\Model\Event;
16
use DERHANSEN\SfEventMgt\Domain\Model\Registration;
17
use DERHANSEN\SfEventMgt\Service\EventCacheService;
18
use DERHANSEN\SfEventMgt\Utility\MessageType;
19
use DERHANSEN\SfEventMgt\Utility\Page;
20
use DERHANSEN\SfEventMgt\Utility\RegistrationResult;
21
use TYPO3\CMS\Core\Utility\ArrayUtility;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Core\Utility\HttpUtility;
24
use TYPO3\CMS\Extbase\Mvc\RequestInterface;
25
use TYPO3\CMS\Extbase\Mvc\ResponseInterface;
26
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
27
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
28
use TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter;
29
use TYPO3\CMS\Fluid\View\StandaloneView;
30
31
/**
32
 * EventController
33
 *
34
 * @author Torben Hansen <[email protected]>
35
 */
36
class EventController extends AbstractController
37
{
38
    /**
39
     * @var EventCacheService
40
     */
41
    protected $eventCacheService = null;
42
43
    /**
44
     * @param EventCacheService $cacheService
45
     */
46
    public function injectEventCacheService(EventCacheService $cacheService)
47
    {
48
        $this->eventCacheService = $cacheService;
49
    }
50
51
    /**
52
     * Assign contentObjectData and pageData to earch view
53
     *
54
     * @param \TYPO3\CMS\Extbase\Mvc\View\ViewInterface $view
55
     */
56
    protected function initializeView(\TYPO3\CMS\Extbase\Mvc\View\ViewInterface $view)
57
    {
58
        $view->assign('contentObjectData', $this->configurationManager->getContentObject()->data);
59
        if (is_object($GLOBALS['TSFE'])) {
60
            $view->assign('pageData', $GLOBALS['TSFE']->page);
61
        }
62
        parent::initializeView($view);
63
    }
64
65
    /**
66
     * Initializes the current action
67
     */
68
    public function initializeAction()
69
    {
70
        $typoScriptFrontendController = $this->getTypoScriptFrontendController();
71
        if ($typoScriptFrontendController !== null) {
72
            static $cacheTagsSet = false;
73
74
            if (!$cacheTagsSet) {
75
                $typoScriptFrontendController->addCacheTags(['tx_sfeventmgt']);
76
                $cacheTagsSet = true;
77
            }
78
        }
79
    }
80
81
    /**
82
     * Creates an event demand object with the given settings
83
     *
84
     * @param array $settings The settings
85
     *
86
     * @return \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand
87
     */
88
    public function createEventDemandObjectFromSettings(array $settings)
89
    {
90
        /** @var \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $demand */
91
        $demand = $this->objectManager->get(EventDemand::class);
92
        $demand->setDisplayMode($settings['displayMode']);
93
        $demand->setStoragePage(Page::extendPidListByChildren($settings['storagePage'], $settings['recursive']));
94
        $demand->setCategoryConjunction($settings['categoryConjunction']);
95
        $demand->setCategory($settings['category']);
96
        $demand->setIncludeSubcategories($settings['includeSubcategories']);
97
        $demand->setTopEventRestriction((int)$settings['topEventRestriction']);
98
        $demand->setOrderField($settings['orderField']);
99
        $demand->setOrderFieldAllowed($settings['orderFieldAllowed']);
100
        $demand->setOrderDirection($settings['orderDirection']);
101
        $demand->setQueryLimit($settings['queryLimit']);
102
        $demand->setLocation($settings['location']);
103
        $demand->setOrganisator($settings['organisator']);
104
        $demand->setSpeaker($settings['speaker']);
105
106
        return $demand;
107
    }
108
109
    /**
110
     * Creates a foreign record demand object with the given settings
111
     *
112
     * @param array $settings The settings
113
     *
114
     * @return \DERHANSEN\SfEventMgt\Domain\Model\Dto\ForeignRecordDemand
115
     */
116
    public function createForeignRecordDemandObjectFromSettings(array $settings)
117
    {
118
        /** @var \DERHANSEN\SfEventMgt\Domain\Model\Dto\ForeignRecordDemand $demand */
119
        $demand = $this->objectManager->get(ForeignRecordDemand::class);
120
        $demand->setStoragePage(Page::extendPidListByChildren($settings['storagePage'], $settings['recursive']));
121
        $demand->setRestrictForeignRecordsToStoragePage((bool)$settings['restrictForeignRecordsToStoragePage']);
122
123
        return $demand;
124
    }
125
126
    /**
127
     * Creates a category demand object with the given settings
128
     *
129
     * @param array $settings The settings
130
     *
131
     * @return \DERHANSEN\SfEventMgt\Domain\Model\Dto\CategoryDemand
132
     */
133
    public function createCategoryDemandObjectFromSettings(array $settings)
134
    {
135
        /** @var \DERHANSEN\SfEventMgt\Domain\Model\Dto\CategoryDemand $demand */
136
        $demand = $this->objectManager->get(CategoryDemand::class);
137 1
        $demand->setStoragePage(Page::extendPidListByChildren($settings['storagePage'], $settings['recursive']));
138
        $demand->setRestrictToStoragePage((bool)$settings['restrictForeignRecordsToStoragePage']);
139
        $demand->setCategories($settings['categoryMenu']['categories']);
140 1
        $demand->setIncludeSubcategories($settings['categoryMenu']['includeSubcategories']);
141 1
142 1
        return $demand;
143 1
    }
144 1
145 1
    /**
146 1
     * Hook into request processing and catch exceptions
147 1
     *
148 1
     * @param RequestInterface $request
149 1
     * @param ResponseInterface $response
150 1
     * @throws \Exception
151
     */
152
    public function processRequest(RequestInterface $request, ResponseInterface $response)
153
    {
154
        try {
155
            parent::processRequest($request, $response);
156
        } catch (\Exception $exception) {
157
            $this->handleKnownExceptionsElseThrowAgain($exception);
158
        }
159
    }
160
161
    /**
162
     * Handle known exceptions
163
     *
164
     * @param \Exception $exception
165
     * @throws \Exception
166
     */
167
    private function handleKnownExceptionsElseThrowAgain(\Exception $exception)
168
    {
169
        $previousException = $exception->getPrevious();
170
        $actions = ['detailAction', 'registrationAction', 'icalDownloadAction'];
171
        if (in_array($this->actionMethodName, $actions, true)
172
            && $previousException instanceof \TYPO3\CMS\Extbase\Property\Exception
173
        ) {
174
            $this->handleEventNotFoundError($this->settings);
175
        } else {
176 1
            throw $exception;
177
        }
178
    }
179 1
180 1
    /**
181 1
     * Initialize list action and set format
182 1
     *
183 1
     * @return void
184 1
     */
185
    public function initializeListAction()
186
    {
187
        if (isset($this->settings['list']['format'])) {
188
            $this->request->setFormat($this->settings['list']['format']);
189
        }
190
    }
191
192
    /**
193
     * List view
194
     *
195 2
     * @param array $overwriteDemand OverwriteDemand
196
     *
197 2
     * @return void
198 2
     */
199 2
    public function listAction(array $overwriteDemand = [])
200
    {
201 2
        $eventDemand = $this->createEventDemandObjectFromSettings($this->settings);
202 2
        $foreignRecordDemand = $this->createForeignRecordDemandObjectFromSettings($this->settings);
203 2
        $categoryDemand = $this->createCategoryDemandObjectFromSettings($this->settings);
204 2
        if ($this->isOverwriteDemand($overwriteDemand)) {
205
            $eventDemand = $this->overwriteEventDemandObject($eventDemand, $overwriteDemand);
206
        }
207
        $events = $this->eventRepository->findDemanded($eventDemand);
208
        $categories = $this->categoryRepository->findDemanded($categoryDemand);
209
        $locations = $this->locationRepository->findDemanded($foreignRecordDemand);
210
        $organisators = $this->organisatorRepository->findDemanded($foreignRecordDemand);
211
        $speakers = $this->speakerRepository->findDemanded($foreignRecordDemand);
212
213
        $values = [
214
            'events' => $events,
215
            'categories' => $categories,
216
            'locations' => $locations,
217
            'organisators' => $organisators,
218
            'speakers' => $speakers,
219
            'overwriteDemand' => $overwriteDemand,
220
            'eventDemand' => $eventDemand
221
        ];
222
223
        $this->signalDispatch(__CLASS__, __FUNCTION__ . 'BeforeRenderView', [&$values, $this]);
224
        $this->view->assignMultiple($values);
225
226 3
        $this->eventCacheService->addPageCacheTagsByEventDemandObject($eventDemand);
227
    }
228 3
229 3
    /**
230 3
     * Calendar view
231 3
     *
232 1
     * @param array $overwriteDemand OverwriteDemand
233 1
     *
234 3
     * @return void
235 3
     */
236 3
    public function calendarAction(array $overwriteDemand = [])
237 3
    {
238 3
        $eventDemand = $this->createEventDemandObjectFromSettings($this->settings);
239 3
        $foreignRecordDemand = $this->createForeignRecordDemandObjectFromSettings($this->settings);
240 3
        $categoryDemand = $this->createCategoryDemandObjectFromSettings($this->settings);
241 3
        if ($this->isOverwriteDemand($overwriteDemand)) {
242
            $eventDemand = $this->overwriteEventDemandObject($eventDemand, $overwriteDemand);
243
        }
244
245
        // Set month/year to demand if not given
246
        if (!$eventDemand->getMonth()) {
247
            $currentMonth = date('n');
248
            $eventDemand->setMonth($currentMonth);
249
        } else {
250 1
            $currentMonth = $eventDemand->getMonth();
251
        }
252 1
        if (!$eventDemand->getYear()) {
253 1
            $currentYear = date('Y');
254
            $eventDemand->setYear($currentYear);
255
        } else {
256
            $currentYear = $eventDemand->getYear();
257
        }
258
259
        // Set demand from calendar date range instead of month / year
260
        if ((bool)$this->settings['calendar']['includeEventsForEveryDayOfAllCalendarWeeks']) {
261
            $eventDemand = $this->changeEventDemandToFullMonthDateRange($eventDemand);
262 1
        }
263
264 1
        $events = $this->eventRepository->findDemanded($eventDemand);
265 1
        $weeks = $this->calendarService->getCalendarArray(
266
            $currentMonth,
267
            $currentYear,
268
            strtotime('today midnight'),
269
            (int)$this->settings['calendar']['firstDayOfWeek'],
270
            $events
271
        );
272
273
        $values = [
274
            'weeks' => $weeks,
275 1
            'categories' => $this->categoryRepository->findDemanded($categoryDemand),
276
            'locations' => $this->locationRepository->findDemanded($foreignRecordDemand),
277 1
            'organisators' => $this->organisatorRepository->findDemanded($foreignRecordDemand),
278
            'eventDemand' => $eventDemand,
279
            'overwriteDemand' => $overwriteDemand,
280 1
            'currentPageId' => $GLOBALS['TSFE']->id,
281
            'firstDayOfMonth' => \DateTime::createFromFormat('d.m.Y', sprintf('1.%s.%s', $currentMonth, $currentYear)),
282 1
            'previousMonthConfig' => $this->calendarService->getDateConfig($currentMonth, $currentYear, '-1 month'),
283 1
            'nextMonthConfig' => $this->calendarService->getDateConfig($currentMonth, $currentYear, '+1 month')
284 1
        ];
285
286
        $this->signalDispatch(__CLASS__, __FUNCTION__ . 'BeforeRenderView', [&$values, $this]);
287
        $this->view->assignMultiple($values);
288
    }
289
290
    /**
291 1
     * Changes the given event demand object to select a date range for a calendar month including days of the previous
292
     * month for the first week and they days for the next month for the last week
293 1
     *
294 1
     * @param EventDemand $eventDemand
295 1
     * @return EventDemand
296 1
     */
297 1
    protected function changeEventDemandToFullMonthDateRange(EventDemand $eventDemand)
298 1
    {
299 1
        $calendarDateRange = $this->calendarService->getCalendarDateRange(
300 1
            $eventDemand->getMonth(),
301
            $eventDemand->getYear(),
302
            $this->settings['calendar']['firstDayOfWeek']
303
        );
304
305
        $eventDemand->setMonth(0);
306
        $eventDemand->setYear(0);
307
308
        $startDate = new \DateTime();
309
        $startDate->setTimestamp($calendarDateRange['firstDayOfCalendar']);
310
        $endDate = new \DateTime();
311 11
        $endDate->setTimestamp($calendarDateRange['lastDayOfCalendar']);
312
        $endDate->setTime(23, 59, 59);
313 11
314 11
        $searchDemand = new SearchDemand();
315 11
        $searchDemand->setStartDate($startDate);
316
        $searchDemand->setEndDate($endDate);
317
        $eventDemand->setSearchDemand($searchDemand);
318 11
319 4
        return $eventDemand;
320 4
    }
321 4
322 4
    /**
323 4
     * Detail view for an event
324 4
     *
325
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
326 4
     * @return mixed string|void
327 4
     */
328 4
    public function detailAction(Event $event = null)
329 4
    {
330
        $event = $this->evaluateSingleEventSetting($event);
331 4
        if (is_a($event, Event::class) && $this->settings['detail']['checkPidOfEventRecord']) {
332 4
            $event = $this->checkPidOfEventRecord($event);
0 ignored issues
show
Documentation introduced by
$event is of type null|object, but the function expects a object<DERHANSEN\SfEventMgt\Domain\Model\Event>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
333 4
        }
334 4
335 4
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
336 4
            return $this->handleEventNotFoundError($this->settings);
337 4
        }
338 4
        $values = ['event' => $event];
339
        $this->signalDispatch(__CLASS__, __FUNCTION__ . 'BeforeRenderView', [&$values, $this]);
340
        $this->view->assignMultiple($values);
341 4
        if ($event !== null) {
342
            $this->eventCacheService->addCacheTagsByEventRecords([$event]);
343
        }
344 4
    }
345 1
346 1
    /**
347 1
     * Error handling if event is not found
348 3
     *
349 3
     * @param array $settings
350
     * @return string
351 4
     */
352
    protected function handleEventNotFoundError($settings)
353
    {
354 4
        if (empty($settings['event']['errorHandling'])) {
355 3
            return null;
356 3
        }
357 3
358 3
        $configuration = GeneralUtility::trimExplode(',', $settings['event']['errorHandling'], true);
359
360 3
        switch ($configuration[0]) {
361 3
            case 'redirectToListView':
362 3
                $listPid = (int)$settings['listPid'] > 0 ? (int)$settings['listPid'] : 1;
363 3
                $this->redirect('list', null, null, null, $listPid);
364 3
                break;
365
            case 'pageNotFoundHandler':
366 3
                $GLOBALS['TSFE']->pageNotFoundAndExit('Event not found.');
367 3
                break;
368
            case 'showStandaloneTemplate':
369
                if (isset($configuration[2])) {
370 4
                    $statusCode = constant(HttpUtility::class . '::HTTP_STATUS_' . $configuration[2]);
371 1
                    HttpUtility::setResponseCode($statusCode);
372 1
                }
373
                $standaloneTemplate = $this->objectManager->get(StandaloneView::class);
374
                $standaloneTemplate->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($configuration[1]));
375 4
376 4
                return $standaloneTemplate->render();
377
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
378 11
            default:
379 1
        }
380 1
    }
381 1
382 1
    /**
383
     * Initiates the iCalendar download for the given event
384 1
     *
385 1
     * @param Event $event The event
386 1
     *
387 1
     * @return string|false
388 1
     */
389 10
    public function icalDownloadAction(Event $event = null)
390 10
    {
391 10
        if (is_a($event, Event::class) && $this->settings['detail']['checkPidOfEventRecord']) {
392 10
            $event = $this->checkPidOfEventRecord($event);
0 ignored issues
show
Bug introduced by
It seems like $event defined by $this->checkPidOfEventRecord($event) on line 392 can be null; however, DERHANSEN\SfEventMgt\Con...checkPidOfEventRecord() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
393 10
        }
394 10
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
395
            return $this->handleEventNotFoundError($this->settings);
396 11
        }
397
        $this->icalendarService->downloadiCalendarFile($event);
0 ignored issues
show
Bug introduced by
It seems like $event can be null; however, downloadiCalendarFile() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
398
        exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method icalDownloadAction() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
399
    }
400
401
    /**
402
     * Registration view for an event
403
     *
404
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
405 9
     *
406
     * @return mixed string|void
407
     */
408 9
    public function registrationAction(Event $event = null)
409 1
    {
410 1
        $event = $this->evaluateSingleEventSetting($event);
411 1
        if (is_a($event, Event::class) && $this->settings['registration']['checkPidOfEventRecord']) {
412 8
            $event = $this->checkPidOfEventRecord($event);
0 ignored issues
show
Documentation introduced by
$event is of type null|object, but the function expects a object<DERHANSEN\SfEventMgt\Domain\Model\Event>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
413
        }
414
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
415
            return $this->handleEventNotFoundError($this->settings);
416 8
        }
417 1
        if ($event->getRestrictPaymentMethods()) {
418 1
            $paymentMethods = $this->paymentService->getRestrictedPaymentMethods($event);
0 ignored issues
show
Documentation introduced by
$event is of type object|null, but the function expects a object<DERHANSEN\SfEventMgt\Domain\Model\Event>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
419 1
        } else {
420 7
            $paymentMethods = $this->paymentService->getPaymentMethods();
421 1
        }
422 1
423 1
        $values = [
424 6
            'event' => $event,
425 1
            'paymentMethods' => $paymentMethods,
426 1
        ];
427 1
428 5
        $this->signalDispatch(__CLASS__, __FUNCTION__ . 'BeforeRenderView', [&$values, $this]);
429 1
        $this->view->assignMultiple($values);
430 1
    }
431 1
432 4
    /**
433 1
     * Processes incoming registrations fields and adds field values to arguments
434 1
     *
435 1
     * @return void
436 3
     */
437 1
    protected function setRegistrationFieldValuesToArguments()
438 1
    {
439 1
        $arguments = $this->request->getArguments();
440 2
        if (!isset($arguments['registration']['fields']) || !isset($arguments['event'])) {
441 1
            return;
442 1
        }
443 1
444 1
        $registrationMvcArgument = $this->arguments->getArgument('registration');
445 1
        $propertyMapping = $registrationMvcArgument->getPropertyMappingConfiguration();
446 1
        $propertyMapping->allowProperties('fieldValues');
447 1
        $propertyMapping->allowCreationForSubProperty('fieldValues');
448
        $propertyMapping->allowModificationForSubProperty('fieldValues');
449 9
450 9
        // allow creation of new objects (for validation)
451 9
        $propertyMapping->setTypeConverterOptions(
452
            PersistentObjectConverter::class,
453
            [
454
                PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED => true,
455
                PersistentObjectConverter::CONFIGURATION_MODIFICATION_ALLOWED => true
456
            ]
457
        );
458
459
        // Set event to registration (required for validation)
460
        $event = $this->eventRepository->findByUid((int)$this->request->getArgument('event'));
461 3
        $propertyMapping->allowProperties('event');
462
        $propertyMapping->allowCreationForSubProperty('event');
463
        $propertyMapping->allowModificationForSubProperty('event');
464 3
        $arguments['registration']['event'] = (int)$this->request->getArgument('event');
465
466 3
        $index = 0;
467 2
        foreach ((array)$arguments['registration']['fields'] as $fieldUid => $value) {
468 2
            // Only accept registration fields of the current event
469
            if (!in_array((int)$fieldUid, $event->getRegistrationFieldsUids(), true)) {
470 2
                continue;
471 2
            }
472 1
473 1
            // allow subvalues in new property mapper
474
            $propertyMapping->forProperty('fieldValues')->allowProperties($index);
475
            $propertyMapping->forProperty('fieldValues.' . $index)->allowAllProperties();
476 2
            $propertyMapping->allowCreationForSubProperty('fieldValues.' . $index);
477 2
            $propertyMapping->allowModificationForSubProperty('fieldValues.' . $index);
478 2
479 2
            if (is_array($value)) {
480
                if (empty($value)) {
481 2
                    $value = '';
482 2
                } else {
483 2
                    $value = json_encode($value);
484 2
                }
485 2
            }
486
487 2
            /** @var Registration\Field $field */
488
            $field = $this->fieldRepository->findByUid((int)$fieldUid);
489
490 2
            $arguments['registration']['fieldValues'][$index] = [
491 2
                'pid' => $field->getPid(),
492 2
                'value' => $value,
493 2
                'field' => strval($fieldUid),
494
                'valueType' => $field->getValueType()
495
            ];
496 3
497 3
            $index++;
498
        }
499
500
        // Remove temporary "fields" field
501
        $arguments = ArrayUtility::removeByPath($arguments, 'registration/fields');
502
        $this->request->setArguments($arguments);
503
    }
504
505
    /**
506
     * Set date format for field dateOfBirth
507
     *
508
     * @return void
509
     */
510
    public function initializeSaveRegistrationAction()
511
    {
512
        $this->arguments->getArgument('registration')
513
            ->getPropertyMappingConfiguration()->forProperty('dateOfBirth')
514 3
            ->setTypeConverterOption(
515 3
                DateTimeConverter::class,
516 3
                DateTimeConverter::CONFIGURATION_DATE_FORMAT,
517
                $this->settings['registration']['formatDateOfBirth']
518
            );
519
        $this->setRegistrationFieldValuesToArguments();
520
    }
521
522
    /**
523
     * Saves the registration
524
     *
525
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
526 2
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
527
     * @validate $registration \DERHANSEN\SfEventMgt\Validation\Validator\RegistrationFieldValidator
528
     * @validate $registration \DERHANSEN\SfEventMgt\Validation\Validator\RegistrationValidator
529 2
     *
530
     * @return mixed string|void
531 2
     */
532
    public function saveRegistrationAction(Registration $registration, Event $event)
533 1
    {
534 1
        if (is_a($event, Event::class) && $this->settings['registration']['checkPidOfEventRecord']) {
535 1
            $event = $this->checkPidOfEventRecord($event);
536 1
        }
537
        if (is_null($event) && isset($this->settings['event']['errorHandling'])) {
538 1
            return $this->handleEventNotFoundError($this->settings);
539 1
        }
540 1
        $autoConfirmation = (bool)$this->settings['registration']['autoConfirmation'] || $event->getEnableAutoconfirm();
0 ignored issues
show
Bug introduced by
It seems like $event is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
541 1
        $result = RegistrationResult::REGISTRATION_SUCCESSFUL;
542 1
        list($success, $result) = $this->registrationService->checkRegistrationSuccess($event, $registration, $result);
0 ignored issues
show
Bug introduced by
It seems like $event can be null; however, checkRegistrationSuccess() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
543
544 1
        // Save registration if no errors
545
        if ($success) {
546
            $isWaitlistRegistration = $this->registrationService->isWaitlistRegistration(
547 1
                $event,
0 ignored issues
show
Bug introduced by
It seems like $event defined by $this->checkPidOfEventRecord($event) on line 535 can be null; however, DERHANSEN\SfEventMgt\Ser...sWaitlistRegistration() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
548 1
                $registration->getAmountOfRegistrations()
549 1
            );
550
            $linkValidity = (int)$this->settings['confirmation']['linkValidity'];
551
            if ($linkValidity === 0) {
552 1
                // Use 3600 seconds as default value if not set
553
                $linkValidity = 3600;
554
            }
555 1
            $confirmationUntil = new \DateTime();
556 1
            $confirmationUntil->add(new \DateInterval('PT' . $linkValidity . 'S'));
557 2
558 2
            $registration->setEvent($event);
0 ignored issues
show
Bug introduced by
It seems like $event defined by $this->checkPidOfEventRecord($event) on line 535 can be null; however, DERHANSEN\SfEventMgt\Dom...egistration::setEvent() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
559 2
            $registration->setPid($event->getPid());
560
            $registration->setConfirmationUntil($confirmationUntil);
561
            $registration->setLanguage($GLOBALS['TSFE']->config['config']['language']);
562
            $registration->setFeUser($this->registrationService->getCurrentFeUserObject());
0 ignored issues
show
Documentation introduced by
$this->registrationServi...etCurrentFeUserObject() is of type object|null, but the function expects a object<TYPO3\CMS\Extbase...ain\Model\FrontendUser>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
563
            $registration->setWaitlist($isWaitlistRegistration);
564
            $registration->_setProperty('_languageUid', $this->getSysLanguageUid());
565
            $this->registrationRepository->add($registration);
566 1
567
            // Persist registration, so we have an UID
568 1
            $this->objectManager->get(PersistenceManager::class)->persistAll();
569 1
570 1
            if ($isWaitlistRegistration) {
571 1
                $messageType = MessageType::REGISTRATION_WAITLIST_NEW;
572 1
            } else {
573 1
                $messageType = MessageType::REGISTRATION_NEW;
574 1
            }
575 1
576 1
            // Fix event in registration for language other than default language
577 1
            $this->registrationService->fixRegistrationEvent($registration, $event);
0 ignored issues
show
Bug introduced by
It seems like $event defined by $this->checkPidOfEventRecord($event) on line 535 can be null; however, DERHANSEN\SfEventMgt\Ser...:fixRegistrationEvent() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
578 1
579 1
            $this->signalDispatch(__CLASS__, __FUNCTION__ . 'AfterRegistrationSaved', [$registration, $this]);
580 1
581 1
            // Send notifications to user and admin if confirmation link should be sent
582 1
            if (!$autoConfirmation) {
583 1
                $this->notificationService->sendUserMessage(
584 1
                    $event,
0 ignored issues
show
Bug introduced by
It seems like $event defined by $this->checkPidOfEventRecord($event) on line 535 can be null; however, DERHANSEN\SfEventMgt\Ser...vice::sendUserMessage() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
585
                    $registration,
586
                    $this->settings,
587
                    $messageType
588
                );
589
                $this->notificationService->sendAdminMessage(
590
                    $event,
0 ignored issues
show
Bug introduced by
It seems like $event defined by $this->checkPidOfEventRecord($event) on line 535 can be null; however, DERHANSEN\SfEventMgt\Ser...ice::sendAdminMessage() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
591
                    $registration,
592
                    $this->settings,
593
                    $messageType
594 6
                );
595
            }
596 6
597 6
            // Create given amount of registrations if necessary
598 6
            if ($registration->getAmountOfRegistrations() > 1) {
599 6
                $this->registrationService->createDependingRegistrations($registration);
600
            }
601 6
602 5
            // Flush page cache for event, since new registration has been added
603
            $this->eventCacheService->flushEventCache($event->getUid(), $event->getPid());
604 5
        }
605 1
606 1
        if ($autoConfirmation && $success) {
607
            $this->redirect(
608 5
                'confirmRegistration',
609 1
                null,
610 1
                null,
611 5
                [
612
                    'reguid' => $registration->getUid(),
613 6
                    'hmac' => $this->hashService->generateHmac('reg-' . $registration->getUid())
614 1
                ]
615 1
            );
616
        } else {
617 6
            $this->redirect(
618 6
                'saveRegistrationResult',
619
                null,
620 6
                null,
621
                [
622 6
                    'result' => $result,
623 6
                    'eventuid' => $event->getUid(),
624 6
                    'hmac' => $this->hashService->generateHmac('event-' . $event->getUid())
625 6
                ]
626 6
            );
627 6
        }
628
    }
629
630
    /**
631
     * Shows the result of the saveRegistrationAction
632
     *
633
     * @param int $result Result
634
     * @param int $eventuid
635 9
     * @param string $hmac
636
     *
637 9
     * @return void
638
     */
639
    public function saveRegistrationResultAction($result, $eventuid, $hmac)
640
    {
641
        $event = null;
642
643
        switch ($result) {
644
            case RegistrationResult::REGISTRATION_SUCCESSFUL:
645
                $messageKey = 'event.message.registrationsuccessful';
646
                $titleKey = 'registrationResult.title.successful';
647
                break;
648
            case RegistrationResult::REGISTRATION_SUCCESSFUL_WAITLIST:
649
                $messageKey = 'event.message.registrationwaitlistsuccessful';
650
                $titleKey = 'registrationWaitlistResult.title.successful';
651
                break;
652
            case RegistrationResult::REGISTRATION_FAILED_EVENT_EXPIRED:
653
                $messageKey = 'event.message.registrationfailedeventexpired';
654
                $titleKey = 'registrationResult.title.failed';
655
                break;
656
            case RegistrationResult::REGISTRATION_FAILED_MAX_PARTICIPANTS:
657
                $messageKey = 'event.message.registrationfailedmaxparticipants';
658
                $titleKey = 'registrationResult.title.failed';
659
                break;
660
            case RegistrationResult::REGISTRATION_NOT_ENABLED:
661
                $messageKey = 'event.message.registrationfailednotenabled';
662
                $titleKey = 'registrationResult.title.failed';
663
                break;
664
            case RegistrationResult::REGISTRATION_FAILED_DEADLINE_EXPIRED:
665
                $messageKey = 'event.message.registrationfaileddeadlineexpired';
666
                $titleKey = 'registrationResult.title.failed';
667
                break;
668
            case RegistrationResult::REGISTRATION_FAILED_NOT_ENOUGH_FREE_PLACES:
669
                $messageKey = 'event.message.registrationfailednotenoughfreeplaces';
670
                $titleKey = 'registrationResult.title.failed';
671
                break;
672
            case RegistrationResult::REGISTRATION_FAILED_MAX_AMOUNT_REGISTRATIONS_EXCEEDED:
673
                $messageKey = 'event.message.registrationfailedmaxamountregistrationsexceeded';
674
                $titleKey = 'registrationResult.title.failed';
675
                break;
676
            case RegistrationResult::REGISTRATION_FAILED_EMAIL_NOT_UNIQUE:
677
                $messageKey = 'event.message.registrationfailedemailnotunique';
678
                $titleKey = 'registrationResult.title.failed';
679
                break;
680
            default:
681
                $messageKey = '';
682
                $titleKey = '';
683
        }
684
685
        if (!$this->hashService->validateHmac('event-' . $eventuid, $hmac)) {
686
            $messageKey = 'event.message.registrationsuccessfulwrongeventhmac';
687
            $titleKey = 'registrationResult.title.failed';
688
        } else {
689
            $event = $this->eventRepository->findByUid((int)$eventuid);
690
        }
691
692
        $this->view->assignMultiple([
693
            'messageKey' => $messageKey,
694
            'titleKey' => $titleKey,
695
            'event' => $event,
696
        ]);
697
    }
698
699
    /**
700
     * Confirms the registration if possible and sends e-mails to admin and user
701
     *
702
     * @param int $reguid UID of registration
703
     * @param string $hmac HMAC for parameters
704
     *
705
     * @return void
706
     */
707
    public function confirmRegistrationAction($reguid, $hmac)
708
    {
709
        $event = null;
710
711
        /* @var $registration Registration */
712
        list($failed, $registration, $messageKey, $titleKey) = $this->registrationService->checkConfirmRegistration(
713
            $reguid,
714
            $hmac
715
        );
716
717
        if ($failed === false) {
718
            $registration->setConfirmed(true);
719
            $event = $registration->getEvent();
720
            $this->registrationRepository->update($registration);
721
722
            $this->signalDispatch(__CLASS__, __FUNCTION__ . 'AfterRegistrationConfirmed', [$registration, $this]);
723
724
            $messageType = MessageType::REGISTRATION_CONFIRMED;
725
            if ($registration->getWaitlist()) {
726
                $messageType = MessageType::REGISTRATION_WAITLIST_CONFIRMED;
727
            }
728
729
            // Send notifications to user and admin
730
            $this->notificationService->sendUserMessage(
731
                $registration->getEvent(),
732
                $registration,
733
                $this->settings,
734
                $messageType
735
            );
736
            $this->notificationService->sendAdminMessage(
737
                $registration->getEvent(),
738
                $registration,
739
                $this->settings,
740
                $messageType
741
            );
742
743
            // Confirm registrations depending on main registration if necessary
744
            if ($registration->getAmountOfRegistrations() > 1) {
745
                $this->registrationService->confirmDependingRegistrations($registration);
746
            }
747
        }
748
749
        // Redirect to payment provider if payment/redirect is enabled
750
        $paymentPid = (int)$this->settings['paymentPid'];
751
        if (!$failed && $paymentPid > 0 && $this->registrationService->redirectPaymentEnabled($registration)) {
752
            $this->uriBuilder->reset()
753
                ->setTargetPageUid($paymentPid)
754
                ->setUseCacheHash(false);
755
            $uri = $this->uriBuilder->uriFor(
756
                'redirect',
757
                [
758
                    'registration' => $registration,
759
                    'hmac' => $this->hashService->generateHmac('redirectAction-' . $registration->getUid())
760
                ],
761
                'Payment',
762
                'sfeventmgt',
763
                'Pipayment'
764
            );
765
            $this->redirectToUri($uri);
766
        }
767
768
        $values = [
769
            'messageKey' => $messageKey,
770
            'titleKey' => $titleKey,
771
            'event' => $event,
772
            'registration' => $registration,
773
        ];
774
775
        $this->signalDispatch(__CLASS__, __FUNCTION__ . 'BeforeRenderView', [&$values, $this]);
776
        $this->view->assignMultiple($values);
777
    }
778
779
    /**
780
     * Cancels the registration if possible and sends e-mails to admin and user
781
     *
782
     * @param int $reguid UID of registration
783
     * @param string $hmac HMAC for parameters
784
     *
785
     * @return void
786
     */
787
    public function cancelRegistrationAction($reguid, $hmac)
788
    {
789
        $event = null;
790
791
        /* @var $registration Registration */
792
        list($failed, $registration, $messageKey, $titleKey) = $this->registrationService->checkCancelRegistration($reguid, $hmac);
793
794
        if ($failed === false) {
795
            $event = $registration->getEvent();
796
797
            // Send notifications (must run before cancelling the registration)
798
            $this->notificationService->sendUserMessage(
799
                $registration->getEvent(),
800
                $registration,
801
                $this->settings,
802
                MessageType::REGISTRATION_CANCELLED
803
            );
804
            $this->notificationService->sendAdminMessage(
805
                $registration->getEvent(),
806
                $registration,
807
                $this->settings,
808
                MessageType::REGISTRATION_CANCELLED
809
            );
810
811
            // First cancel depending registrations
812
            if ($registration->getAmountOfRegistrations() > 1) {
813
                $this->registrationService->cancelDependingRegistrations($registration);
814
            }
815
816
            // Finally cancel registration
817
            $this->registrationRepository->remove($registration);
818
819
            // Dispatch signal, so waitlist registrations can be moved up
820
            $this->signalDispatch(__CLASS__, __FUNCTION__ . 'WaitlistMoveUp', [$event, $this]);
821
822
            // Flush page cache for event, since new registration has been added
823
            $this->eventCacheService->flushEventCache($event->getUid(), $event->getPid());
824
        }
825
826
        $values = [
827
            'messageKey' => $messageKey,
828
            'titleKey' => $titleKey,
829
            'event' => $event,
830
        ];
831
832
        $this->signalDispatch(__CLASS__, __FUNCTION__ . 'BeforeRenderView', [&$values, $this]);
833
        $this->view->assignMultiple($values);
834
    }
835
836
    /**
837
     * Set date format for field startDate and endDate
838
     *
839
     * @return void
840
     */
841
    public function initializeSearchAction()
842
    {
843
        if ($this->settings !== null && $this->settings['search']['dateFormat']) {
844
            $this->arguments->getArgument('searchDemand')
845
                ->getPropertyMappingConfiguration()->forProperty('startDate')
846
                ->setTypeConverterOption(
847
                    DateTimeConverter::class,
848
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
849
                    $this->settings['search']['dateFormat']
850
                );
851
            $this->arguments->getArgument('searchDemand')
852
                ->getPropertyMappingConfiguration()->forProperty('endDate')
853
                ->setTypeConverterOption(
854
                    DateTimeConverter::class,
855
                    DateTimeConverter::CONFIGURATION_DATE_FORMAT,
856
                    $this->settings['search']['dateFormat']
857
                );
858
        }
859
        if ($this->arguments->hasArgument('searchDemand')) {
860
            $propertyMappingConfiguration = $this->arguments->getArgument('searchDemand')
861
                ->getPropertyMappingConfiguration();
862
            $propertyMappingConfiguration->allowAllProperties();
863
            $propertyMappingConfiguration->setTypeConverterOption(
864
                PersistentObjectConverter::class,
865
                PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED,
866
                true
867
            );
868
        }
869
    }
870
871
    /**
872
     * Search view
873
     *
874
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\SearchDemand $searchDemand SearchDemand
875
     * @param array $overwriteDemand OverwriteDemand
876
     *
877
     * @return void
878
     */
879
    public function searchAction(SearchDemand $searchDemand = null, array $overwriteDemand = [])
880
    {
881
        $eventDemand = $this->createEventDemandObjectFromSettings($this->settings);
882
        $eventDemand->setSearchDemand($searchDemand);
0 ignored issues
show
Bug introduced by
It seems like $searchDemand defined by parameter $searchDemand on line 879 can be null; however, DERHANSEN\SfEventMgt\Dom...mand::setSearchDemand() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
883
        $foreignRecordDemand = $this->createForeignRecordDemandObjectFromSettings($this->settings);
884
        $categoryDemand = $this->createCategoryDemandObjectFromSettings($this->settings);
885
886
        if ($searchDemand !== null) {
887
            $searchDemand->setFields($this->settings['search']['fields']);
888
889
            if ($this->settings['search']['adjustTime'] && $searchDemand->getStartDate() !== null) {
890
                $searchDemand->getStartDate()->setTime(0, 0, 0);
891
            }
892
893
            if ($this->settings['search']['adjustTime'] && $searchDemand->getEndDate() !== null) {
894
                $searchDemand->getEndDate()->setTime(23, 59, 59);
895
            }
896
        }
897
898
        if ($this->isOverwriteDemand($overwriteDemand)) {
899
            $eventDemand = $this->overwriteEventDemandObject($eventDemand, $overwriteDemand);
900
        }
901
902
        $categories = $this->categoryRepository->findDemanded($categoryDemand);
903
        $locations = $this->locationRepository->findDemanded($foreignRecordDemand);
904
        $organisators = $this->organisatorRepository->findDemanded($foreignRecordDemand);
905
        $speakers = $this->speakerRepository->findDemanded($foreignRecordDemand);
906
        $events = $this->eventRepository->findDemanded($eventDemand);
907
908
        $values = [
909
            'events' => $events,
910
            'categories' => $categories,
911
            'locations' => $locations,
912
            'organisators' => $organisators,
913
            'speakers' => $speakers,
914
            'searchDemand' => $searchDemand,
915
            'overwriteDemand' => $overwriteDemand,
916
        ];
917
918
        $this->signalDispatch(__CLASS__, __FUNCTION__ . 'BeforeRenderView', [&$values, $this]);
919
        $this->view->assignMultiple($values);
920
    }
921
922
    /**
923
     * Returns if a demand object can be overwritten with the given overwriteDemand array
924
     *
925
     * @param array $overwriteDemand
926
     * @return bool
927
     */
928
    protected function isOverwriteDemand($overwriteDemand)
929
    {
930
        return $this->settings['disableOverrideDemand'] != 1 && $overwriteDemand !== [];
931
    }
932
933
    /**
934
     * If no event is given and the singleEvent setting is set, the configured single event is returned
935
     *
936
     * @param Event|null $event
937
     * @return Event|null
938
     */
939
    protected function evaluateSingleEventSetting($event)
940
    {
941
        if ($event === null && (int)$this->settings['singleEvent'] > 0) {
942
            $event = $this->eventRepository->findByUid((int)$this->settings['singleEvent']);
943
        }
944
945
        return $event;
946
    }
947
948
    /**
949
     * Checks if the event pid could be found in the storagePage settings of the detail plugin and
950
     * if the pid could not be found it return null instead of the event object.
951
     *
952
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
953
     * @return null|\DERHANSEN\SfEventMgt\Domain\Model\Event
954
     */
955
    protected function checkPidOfEventRecord(Event $event)
956
    {
957
        $allowedStoragePages = GeneralUtility::trimExplode(
958
            ',',
959
            Page::extendPidListByChildren(
960
                $this->settings['storagePage'],
961
                $this->settings['recursive']
962
            ),
963
            true
964
        );
965
        if (count($allowedStoragePages) > 0 && !in_array($event->getPid(), $allowedStoragePages)) {
966
            $this->signalSlotDispatcher->dispatch(
967
                __CLASS__,
968
                'checkPidOfEventRecordFailedInDetailAction',
969
                [
970
                    'event' => $event,
971
                    'eventController' => $this
972
                ]
973
            );
974
            $event = null;
975
        }
976
977
        return $event;
978
    }
979
980
    /**
981
     * Returns the current sys_language_uid
982
     *
983
     * @return int
984
     */
985
    protected function getSysLanguageUid()
986
    {
987
        return $GLOBALS['TSFE']->sys_language_uid;
988
    }
989
}
990