Passed
Push — master ( da5c3a...138f6a )
by Torben
132:09 queued 128:49
created

EventRepository::setDisplayModeConstraint()   B

Complexity

Conditions 10
Paths 22

Size

Total Lines 46
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 10

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 10
eloc 34
nc 22
nop 3
dl 0
loc 46
ccs 21
cts 21
cp 1
crap 10
rs 7.6666
c 2
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Domain\Repository;
11
12
use DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand;
13
use DERHANSEN\SfEventMgt\Event\ModifyEventQueryConstraintsEvent;
14
use DERHANSEN\SfEventMgt\Service\CategoryService;
15
use Psr\EventDispatcher\EventDispatcherInterface;
16
use TYPO3\CMS\Core\Utility\GeneralUtility;
17
use TYPO3\CMS\Core\Utility\MathUtility;
18
use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings;
19
20
/**
21
 * The repository for Events
22
 */
23
class EventRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
24
{
25
    /**
26
     * Set default sorting
27
     *
28
     * @var array
29
     */
30
    protected $defaultOrderings = [
31
        'startdate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
32
    ];
33
34
    /**
35
     * @var EventDispatcherInterface
36
     */
37
    protected $eventDispatcher;
38
39
    /**
40
     * @param EventDispatcherInterface $eventDispatcher
41
     */
42
    public function injectEventDispatcher(EventDispatcherInterface $eventDispatcher)
43
    {
44
        $this->eventDispatcher = $eventDispatcher;
45 31
    }
46
47 31
    /**
48 31
     * Disable the use of storage records, because the StoragePage can be set
49 31
     * in the plugin
50
     */
51
    public function initializeObject()
52
    {
53
        $this->defaultQuerySettings = $this->objectManager->get(Typo3QuerySettings::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

53
        $this->defaultQuerySettings = /** @scrutinizer ignore-deprecated */ $this->objectManager->get(Typo3QuerySettings::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...
54
        $this->defaultQuerySettings->setRespectStoragePage(false);
55
    }
56
57
    /**
58 30
     * Returns the objects of this repository matching the given demand
59
     *
60 30
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
61 30
     *
62 30
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface QueryResultInterface
63 30
     */
64 30
    public function findDemanded(EventDemand $eventDemand)
65 30
    {
66 30
        $constraints = [];
67 30
        $query = $this->createQuery();
68 30
        $query->getQuerySettings()->setIgnoreEnableFields($eventDemand->getIgnoreEnableFields());
69 30
70 30
        $this->setStoragePageConstraint($query, $eventDemand, $constraints);
71 30
        $this->setDisplayModeConstraint($query, $eventDemand, $constraints);
72
        $this->setCategoryConstraint($query, $eventDemand, $constraints);
73 30
        $this->setLocationConstraint($query, $eventDemand, $constraints);
74 30
        $this->setLocationCityConstraint($query, $eventDemand, $constraints);
75 30
        $this->setLocationCountryConstraint($query, $eventDemand, $constraints);
76
        $this->setSpeakerConstraint($query, $eventDemand, $constraints);
77 30
        $this->setOrganisatorConstraint($query, $eventDemand, $constraints);
78 30
        $this->setStartEndDateConstraint($query, $eventDemand, $constraints);
79
        $this->setSearchConstraint($query, $eventDemand, $constraints);
80
        $this->setTopEventConstraint($query, $eventDemand, $constraints);
81
        $this->setYearMonthDayRestriction($query, $eventDemand, $constraints);
82
83
        $modifyEventQueryConstraintsEvent = new ModifyEventQueryConstraintsEvent(
84
            $constraints,
85
            $query,
86
            $eventDemand,
87
            $this
88
        );
89 30
        $this->eventDispatcher->dispatch($modifyEventQueryConstraintsEvent);
90
        $constraints = $modifyEventQueryConstraintsEvent->getConstraints();
91 30
92 30
        $this->setOrderingsFromDemand($query, $eventDemand);
93 1
94 30
        if (count($constraints) > 0) {
95 1
            $query->matching($query->logicalAnd($constraints));
96 1
        }
97 30
98
        $this->setQueryLimitFromDemand($query, $eventDemand);
99
100
        return $query->execute();
101
    }
102
103
    /**
104
     * Returns the event with the given UID and also respects the hidden state
105
     *
106
     * @param int $uid
107 30
     * @return object
108
     */
109 30
    public function findByUidIncludeHidden(int $uid)
110 30
    {
111 30
        $query = $this->createQuery();
112 30
        $query->getQuerySettings()->setIgnoreEnableFields(true);
113
        $query->matching($query->equals('uid', $uid));
114
        return $query->execute()->getFirst();
115
    }
116
117
    /**
118 30
     * Sets a query limit to the given query for the given demand
119
     *
120
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
121
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
122
     */
123
    protected function setQueryLimitFromDemand($query, EventDemand $eventDemand)
124
    {
125
        if ($eventDemand->getQueryLimit() != null &&
126
            MathUtility::canBeInterpretedAsInteger($eventDemand->getQueryLimit()) &&
127
            (int)$eventDemand->getQueryLimit() > 0
128
        ) {
129 30
            $query->setLimit((int)$eventDemand->getQueryLimit());
130
        }
131 30
    }
132 30
133 30
    /**
134 30
     * Sets the ordering to the given query for the given demand
135 30
     *
136
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
137
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
138
     */
139
    protected function setOrderingsFromDemand($query, EventDemand $eventDemand)
140
    {
141
        $orderings = [];
142
        $orderFieldAllowed = GeneralUtility::trimExplode(',', $eventDemand->getOrderFieldAllowed(), true);
143
        if ($eventDemand->getOrderField() != '' && $eventDemand->getOrderDirection() != '' &&
144
            !empty($orderFieldAllowed) && in_array($eventDemand->getOrderField(), $orderFieldAllowed, true)) {
145
            $orderings[$eventDemand->getOrderField()] = ((strtolower($eventDemand->getOrderDirection()) == 'desc') ?
146 30
                \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING :
147
                \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING);
148 30
            $query->setOrderings($orderings);
149 30
        }
150 1
    }
151 1
152 29
    /**
153 1
     * Sets the storagePage constraint to the given constraints array
154 1
     *
155 28
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
156 30
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
157 30
     * @param array $constraints Constraints
158
     */
159
    protected function setStoragePageConstraint($query, $eventDemand, &$constraints)
160
    {
161
        if ($eventDemand->getStoragePage() !== null && $eventDemand->getStoragePage() !== '') {
162
            $pidList = GeneralUtility::intExplode(',', $eventDemand->getStoragePage(), true);
163
            $constraints['storagePage'] = $query->in('pid', $pidList);
164
        }
165
    }
166
167
    /**
168 30
     * Sets the displayMode constraint to the given constraints array
169
     *
170 30
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
171 5
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
172 5
     * @param array $constraints Constraints
173 1
     */
174 1
    protected function setDisplayModeConstraint($query, $eventDemand, &$constraints)
175 1
    {
176 4
        switch ($eventDemand->getDisplayMode()) {
177
            case 'future':
178 5
                $constraints['displayMode'] = $query->greaterThan('startdate', $eventDemand->getCurrentDateTime());
179 5
                break;
180 5
            case 'current_future':
181 5
                $constraints['displayMode'] = $query->logicalOr([
182 5
                    $query->greaterThan('startdate', $eventDemand->getCurrentDateTime()),
183 5
                    $query->logicalAnd([
184 5
                        $query->greaterThanOrEqual('enddate', $eventDemand->getCurrentDateTime()),
185 30
                        $query->lessThanOrEqual('startdate', $eventDemand->getCurrentDateTime())
186
                    ])
187
                ]);
188
                break;
189
            case 'past':
190
                $constraints['displayMode'] = $query->lessThanOrEqual('enddate', $eventDemand->getCurrentDateTime());
191
                break;
192
            case 'time_restriction':
193
                if (!empty($eventDemand->getTimeRestrictionLow())) {
194
                    $timeRestriction = strtotime($eventDemand->getTimeRestrictionLow());
195
                    $timeRestrictionConstraints['timeRestrictionLow'] = $query->greaterThanOrEqual('startdate', $timeRestriction);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$timeRestrictionConstraints was never initialized. Although not strictly required by PHP, it is generally a good practice to add $timeRestrictionConstraints = array(); before regardless.
Loading history...
196 30
197
                    if ($eventDemand->getIncludeCurrent()) {
198 30
                        $includeCurrentConstraint = $query->logicalAnd([
199 3
                            $query->lessThan('startdate', $timeRestriction),
200 3
                            $query->greaterThan('enddate', $timeRestriction)
201 30
                        ]);
202
                    }
203
                }
204
                if (!empty($eventDemand->getTimeRestrictionHigh())) {
205
                    $timeRestrictionHigh = strtotime($eventDemand->getTimeRestrictionHigh());
206
                    $timeRestrictionConstraints['timeRestrictionHigh'] = $query->lessThanOrEqual('startdate', $timeRestrictionHigh);
207
                }
208
                if (isset($timeRestrictionConstraints)) {
209
                    if ($eventDemand->getIncludeCurrent()) {
210
                        $constraints['displayMode'] = $query->logicalOr([
211
                            $includeCurrentConstraint,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $includeCurrentConstraint does not seem to be defined for all execution paths leading up to this point.
Loading history...
212 30
                            $query->logicalAnd($timeRestrictionConstraints)
213
                        ]);
214 30
                    } else {
215 2
                        $constraints['displayMode'] = $query->logicalAnd($timeRestrictionConstraints);
216 2
                    }
217 30
                }
218
                break;
219
            default:
220
        }
221
    }
222
223
    /**
224
     * Sets the category constraint to the given constraints array
225
     *
226
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
227
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
228 30
     * @param array $constraints Constraints
229
     */
230 30
    protected function setCategoryConstraint($query, $eventDemand, &$constraints)
231 2
    {
232 2
        // If no category constraint is set, categories should not be respected in the query
233 30
        if ($eventDemand->getCategoryConjunction() === '') {
234
            return;
235
        }
236
237
        if ($eventDemand->getCategory() != '') {
238
            $categoryConstraints = [];
239
            if ($eventDemand->getIncludeSubcategories()) {
240
                $categoryList = CategoryService::getCategoryListWithChilds($eventDemand->getCategory());
241
                $categories = GeneralUtility::intExplode(',', $categoryList, true);
242
            } else {
243
                $categories = GeneralUtility::intExplode(',', $eventDemand->getCategory(), true);
244 30
            }
245
            foreach ($categories as $category) {
246
                $categoryConstraints[] = $query->contains('category', $category);
247 30
            }
248 1
            if (count($categoryConstraints) > 0) {
249 1
                $constraints['category'] = $this->getCategoryConstraint($query, $eventDemand, $categoryConstraints);
250
            }
251
        }
252 30
    }
253 1
254 1
    /**
255 30
     * Returns the category constraint depending on the category conjunction configured in eventDemand
256
     *
257
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
258
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand
259
     * @param array $categoryConstraints
260
     * @return mixed
261
     */
262
    public function getCategoryConstraint($query, $eventDemand, $categoryConstraints)
263
    {
264
        switch (strtolower($eventDemand->getCategoryConjunction())) {
265
            case 'and':
266 30
                $constraint = $query->logicalAnd($categoryConstraints);
267
                break;
268 30
            case 'notor':
269 30
                $constraint = $query->logicalNot($query->logicalOr($categoryConstraints));
270 3
                break;
271 30
            case 'notand':
272 1
                $constraint = $query->logicalNot($query->logicalAnd($categoryConstraints));
273 1
                break;
274
            case 'or':
275 1
            default:
276
                $constraint = $query->logicalOr($categoryConstraints);
277
        }
278
279 1
        return $constraint;
280 1
    }
281 1
282 1
    /**
283 1
     * Sets the location constraint to the given constraints array
284 1
     *
285
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
286 1
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
287 1
     * @param array $constraints Constraints
288 1
     */
289 1
    protected function setLocationConstraint($query, $eventDemand, &$constraints)
290 30
    {
291
        if ($eventDemand->getLocation() !== null && $eventDemand->getLocation() != '') {
292
            $constraints['location'] = $query->equals('location', $eventDemand->getLocation());
293
        }
294
    }
295
296
    /**
297
     * Sets the location.city constraint to the given constraints array
298
     *
299
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
300
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
301 30
     * @param array $constraints Constraints
302
     */
303 30
    protected function setLocationCityConstraint($query, $eventDemand, &$constraints)
304 2
    {
305 2
        if ($eventDemand->getLocationCity() !== null && $eventDemand->getLocationCity() != '') {
306 30
            $constraints['locationCity'] = $query->equals('location.city', $eventDemand->getLocationCity());
307
        }
308
    }
309
310
    /**
311
     * Sets the location.country constraint to the given constraints array
312
     *
313
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
314
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
315
     * @param array $constraints Constraints
316
     */
317
    protected function setLocationCountryConstraint($query, $eventDemand, &$constraints)
318
    {
319
        if ($eventDemand->getLocationCountry() !== null && $eventDemand->getLocationCountry() != '') {
320
            $constraints['locationCountry'] = $query->equals('location.country', $eventDemand->getLocationCountry());
321
        }
322
    }
323
324
    /**
325
     * Sets the speaker constraint to the given constraints array
326
     *
327
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
328
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
329
     * @param array $constraints Constraints
330
     */
331
    protected function setSpeakerConstraint($query, $eventDemand, &$constraints)
332
    {
333
        if ($eventDemand->getSpeaker() !== null && $eventDemand->getSpeaker() != '') {
334
            $constraints['speaker'] = $query->contains('speaker', $eventDemand->getSpeaker());
335
        }
336
    }
337
338
    /**
339
     * Sets the organisator constraint to the given constraints array
340
     *
341
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
342
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
343
     * @param array $constraints Constraints
344
     */
345
    protected function setOrganisatorConstraint($query, $eventDemand, &$constraints)
346
    {
347
        if ($eventDemand->getOrganisator() !== null && $eventDemand->getOrganisator() != '') {
348
            $constraints['organisator'] = $query->equals('organisator', $eventDemand->getOrganisator());
349
        }
350
    }
351
352
    /**
353
     * Sets the start- and enddate constraint to the given constraints array
354
     *
355
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
356
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
357
     * @param array $constraints Constraints
358
     */
359
    protected function setStartEndDateConstraint($query, $eventDemand, &$constraints)
360
    {
361
        if ($eventDemand->getSearchDemand() && $eventDemand->getSearchDemand()->getStartDate() !== null &&
362
            $eventDemand->getSearchDemand()->getEndDate() !== null
363
        ) {
364
            /* StartDate and EndDate  - Search for events between two given dates */
365
            $begin = $eventDemand->getSearchDemand()->getStartDate();
366
            $end = $eventDemand->getSearchDemand()->getEndDate();
367
            $constraints['startEndDate'] = $query->logicalOr([
368
                $query->between('startdate', $begin, $end),
369
                $query->between('enddate', $begin, $end),
370
                $query->logicalAnd([
371
                    $query->greaterThanOrEqual('enddate', $begin),
372
                    $query->lessThanOrEqual('startdate', $begin)
373
                ])
374
            ]);
375
        } elseif ($eventDemand->getSearchDemand() && $eventDemand->getSearchDemand()->getStartDate() !== null) {
376
            /* StartDate - Search for events beginning at a given date */
377
            $constraints['startDate'] = $query->greaterThanOrEqual('startdate', $eventDemand->getSearchDemand()->getStartDate());
378
        } elseif ($eventDemand->getSearchDemand() && $eventDemand->getSearchDemand()->getEndDate() !== null) {
379
            /* EndDate - Search for events ending on a given date */
380
            $constraints['endDate'] = $query->lessThanOrEqual('enddate', $eventDemand->getSearchDemand()->getEndDate());
381
        }
382
    }
383
384
    /**
385
     * Sets the search constraint to the given constraints array
386
     *
387
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
388
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
389
     * @param array $constraints Constraints
390
     */
391
    protected function setSearchConstraint($query, $eventDemand, &$constraints)
392
    {
393
        if ($eventDemand->getSearchDemand() &&
394
            $eventDemand->getSearchDemand()->getSearch() !== null &&
395
            $eventDemand->getSearchDemand()->getSearch() !== ''
396
        ) {
397
            $searchFields = GeneralUtility::trimExplode(',', $eventDemand->getSearchDemand()->getFields(), true);
398
            $searchConstraints = [];
399
400
            if (count($searchFields) === 0) {
401
                throw new \UnexpectedValueException('No search fields defined', 1318497755);
402
            }
403
404
            $searchSubject = $eventDemand->getSearchDemand()->getSearch();
405
            foreach ($searchFields as $field) {
406
                if (!empty($searchSubject)) {
407
                    $searchConstraints[] = $query->like($field, '%' . addcslashes($searchSubject, '_%') . '%');
408
                }
409
            }
410
411
            if (count($searchConstraints)) {
412
                $constraints['search'] = $query->logicalOr($searchConstraints);
413
            }
414
        }
415
    }
416
417
    /**
418
     * Sets the topEvent constraint to the given constraints array
419
     *
420
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
421
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
422
     * @param array $constraints Constraints
423
     */
424
    protected function setTopEventConstraint($query, $eventDemand, &$constraints)
425
    {
426
        if ($eventDemand->getTopEventRestriction() > 0) {
427
            $constraints['topEvent'] = $query->equals('topEvent', (bool)($eventDemand->getTopEventRestriction() - 1));
428
        }
429
    }
430
431
    /**
432
     * Sets the restriction for year, year/month or year/month/day to the given constraints array
433
     *
434
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
435
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand
436
     * @param array $constraints
437
     */
438
    protected function setYearMonthDayRestriction($query, $eventDemand, &$constraints)
439
    {
440
        if ($eventDemand->getYear() > 0) {
441
            if ($eventDemand->getMonth() > 0) {
442
                if ($eventDemand->getDay() > 0) {
443
                    $begin = mktime(0, 0, 0, $eventDemand->getMonth(), $eventDemand->getDay(), $eventDemand->getYear());
444
                    $end = mktime(23, 59, 59, $eventDemand->getMonth(), $eventDemand->getDay(), $eventDemand->getYear());
445
                } else {
446
                    $begin = mktime(0, 0, 0, $eventDemand->getMonth(), 1, $eventDemand->getYear());
447
                    $end = mktime(23, 59, 59, ($eventDemand->getMonth() + 1), 0, $eventDemand->getYear());
448
                }
449
            } else {
450
                $begin = mktime(0, 0, 0, 1, 1, $eventDemand->getYear());
451
                $end = mktime(23, 59, 59, 12, 31, $eventDemand->getYear());
452
            }
453
            $constraints['yearMonthDay'] = $query->logicalOr([
454
                $query->between('startdate', $begin, $end),
455
                $query->between('enddate', $begin, $end),
456
                $query->logicalAnd([
457
                    $query->greaterThanOrEqual('enddate', $begin),
458
                    $query->lessThanOrEqual('startdate', $begin)
459
                ])
460
            ]);
461
        }
462
    }
463
}
464