Completed
Push — development ( df9f5f...c4e421 )
by Torben
03:18
created

EventRepository   F

Complexity

Total Complexity 68

Size/Duplication

Total Lines 414
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 99.17%

Importance

Changes 0
Metric Value
wmc 68
lcom 1
cbo 9
dl 0
loc 414
ccs 119
cts 120
cp 0.9917
rs 2.96
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A initializeObject() 0 5 1
A findDemanded() 0 35 2
A setQueryLimitFromDemand() 0 9 4
A setOrderingsFromDemand() 0 12 6
A setDisplayModeConstraint() 0 21 4
B setCategoryConstraint() 0 23 6
A getCategoryConstraint() 0 19 5
A setLocationConstraint() 0 6 3
A setLocationCityConstraint() 0 6 3
A setLocationCountryConstraint() 0 6 3
A setSpeakerConstraint() 0 6 3
A setOrganisatorConstraint() 0 6 3
A setStoragePageConstraint() 0 7 3
B setStartEndDateConstraint() 0 24 8
B setSearchConstraint() 0 25 8
A setTopEventConstraint() 0 6 2
A setYearMonthDayRestriction() 0 25 4

How to fix   Complexity   

Complex Class

Complex classes like EventRepository 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 EventRepository, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace DERHANSEN\SfEventMgt\Domain\Repository;
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\EventDemand;
12
use DERHANSEN\SfEventMgt\Service\CategoryService;
13
use TYPO3\CMS\Core\Utility\GeneralUtility;
14
use TYPO3\CMS\Core\Utility\MathUtility;
15
use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings;
16
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
17
18
/**
19
 * The repository for Events
20
 *
21
 * @author Torben Hansen <[email protected]>
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
     * Disable the use of storage records, because the StoragePage can be set
36
     * in the plugin
37
     *
38
     * @return void
39
     */
40
    public function initializeObject()
41
    {
42
        $this->defaultQuerySettings = $this->objectManager->get(Typo3QuerySettings::class);
43
        $this->defaultQuerySettings->setRespectStoragePage(false);
44
    }
45 31
46
    /**
47 31
     * Returns the objects of this repository matching the given demand
48 31
     *
49 31
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
50
     *
51
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface QueryResultInterface
52
     */
53
    public function findDemanded(EventDemand $eventDemand)
54
    {
55
        $constraints = [];
56
        $query = $this->createQuery();
57
        $this->setStoragePageConstraint($query, $eventDemand, $constraints);
58 30
        $this->setDisplayModeConstraint($query, $eventDemand, $constraints);
59
        $this->setCategoryConstraint($query, $eventDemand, $constraints);
60 30
        $this->setLocationConstraint($query, $eventDemand, $constraints);
61 30
        $this->setLocationCityConstraint($query, $eventDemand, $constraints);
62 30
        $this->setLocationCountryConstraint($query, $eventDemand, $constraints);
63 30
        $this->setSpeakerConstraint($query, $eventDemand, $constraints);
64 30
        $this->setOrganisatorConstraint($query, $eventDemand, $constraints);
65 30
        $this->setStartEndDateConstraint($query, $eventDemand, $constraints);
66 30
        $this->setSearchConstraint($query, $eventDemand, $constraints);
67 30
        $this->setTopEventConstraint($query, $eventDemand, $constraints);
68 30
        $this->setYearMonthDayRestriction($query, $eventDemand, $constraints);
69 30
70 30
        /** @var Dispatcher $signalSlotDispatcher */
71 30
        $signalSlotDispatcher = $this->objectManager->get(Dispatcher::class);
72
        $signalSlotDispatcher->dispatch(
73 30
            __CLASS__,
74 30
            __FUNCTION__ . 'ModifyQueryConstraints',
75 30
            [&$constraints, $query, $eventDemand, $this]
76
        );
77 30
78 30
        $this->setOrderingsFromDemand($query, $eventDemand);
79
80
        if (count($constraints) > 0) {
81
            $query->matching($query->logicalAnd($constraints));
82
        }
83
84
        $this->setQueryLimitFromDemand($query, $eventDemand);
85
86
        return $query->execute();
87
    }
88
89 30
    /**
90
     * Sets a query limit to the given query for the given demand
91 30
     *
92 30
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
93 1
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
94 30
     *
95 1
     * @return void
96 1
     */
97 30
    protected function setQueryLimitFromDemand($query, EventDemand $eventDemand)
98
    {
99
        if ($eventDemand->getQueryLimit() != null &&
100
            MathUtility::canBeInterpretedAsInteger($eventDemand->getQueryLimit()) &&
101
            (int)$eventDemand->getQueryLimit() > 0
102
        ) {
103
            $query->setLimit((int)$eventDemand->getQueryLimit());
104
        }
105
    }
106
107 30
    /**
108
     * Sets the ordering to the given query for the given demand
109 30
     *
110 30
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
111 6
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
112 6
     *
113 3
     * @return void
114 6
     */
115 6
    protected function setOrderingsFromDemand($query, EventDemand $eventDemand)
116 30
    {
117
        $orderings = [];
118
        $orderFieldAllowed = GeneralUtility::trimExplode(',', $eventDemand->getOrderFieldAllowed(), true);
119
        if ($eventDemand->getOrderField() != '' && $eventDemand->getOrderDirection() != '' &&
120
            !empty($orderFieldAllowed) && in_array($eventDemand->getOrderField(), $orderFieldAllowed, true)) {
121
            $orderings[$eventDemand->getOrderField()] = ((strtolower($eventDemand->getOrderDirection()) == 'desc') ?
122
                \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING :
123
                \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING);
124
            $query->setOrderings($orderings);
125
        }
126
    }
127 30
128
    /**
129 30
     * Sets the storagePage constraint to the given constraints array
130 30
     *
131 30
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
132 30
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
133 30
     * @param array $constraints Constraints
134
     *
135
     * @return void
136
     */
137
    protected function setStoragePageConstraint($query, $eventDemand, &$constraints)
138
    {
139
        if ($eventDemand->getStoragePage() && $eventDemand->getStoragePage() !== '') {
140
            $pidList = GeneralUtility::intExplode(',', $eventDemand->getStoragePage(), true);
141
            $constraints[] = $query->in('pid', $pidList);
142
        }
143
    }
144 30
145
    /**
146 30
     * Sets the displayMode constraint to the given constraints array
147 30
     *
148 1
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
149 1
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
150 29
     * @param array $constraints Constraints
151 1
     *
152 1
     * @return void
153 28
     */
154 30
    protected function setDisplayModeConstraint($query, $eventDemand, &$constraints)
155 30
    {
156
        switch ($eventDemand->getDisplayMode()) {
157
            case 'future':
158
                $constraints[] = $query->greaterThan('startdate', $eventDemand->getCurrentDateTime());
159
                break;
160
            case 'current_future':
161
                $constraints[] = $query->logicalOr([
162
                    $query->greaterThan('startdate', $eventDemand->getCurrentDateTime()),
163
                    $query->logicalAnd([
164
                        $query->greaterThanOrEqual('enddate', $eventDemand->getCurrentDateTime()),
165
                        $query->lessThanOrEqual('startdate', $eventDemand->getCurrentDateTime())
166 30
                    ])
167
                ]);
168 30
                break;
169 5
            case 'past':
170 5
                $constraints[] = $query->lessThanOrEqual('enddate', $eventDemand->getCurrentDateTime());
171 1
                break;
172 1
            default:
173 1
        }
174 4
    }
175
176 5
    /**
177 5
     * Sets the category constraint to the given constraints array
178 5
     *
179 5
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
180 5
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
181 5
     * @param array $constraints Constraints
182 5
     *
183 30
     * @return void
184
     */
185
    protected function setCategoryConstraint($query, $eventDemand, &$constraints)
186
    {
187
        // If no category constraint is set, categories should not be respected in the query
188
        if ($eventDemand->getCategoryConjunction() === '') {
189
            return;
190
        }
191
192
        if ($eventDemand->getCategory() != '') {
193
            $categoryConstraints = [];
194 30
            if ($eventDemand->getIncludeSubcategories()) {
195
                $categoryList = CategoryService::getCategoryListWithChilds($eventDemand->getCategory());
196 30
                $categories = GeneralUtility::intExplode(',', $categoryList, true);
197 3
            } else {
198 3
                $categories = GeneralUtility::intExplode(',', $eventDemand->getCategory(), true);
199 30
            }
200
            foreach ($categories as $category) {
201
                $categoryConstraints[] = $query->contains('category', $category);
202
            }
203
            if (count($categoryConstraints) > 0) {
204
                $constraints[] = $this->getCategoryConstraint($query, $eventDemand, $categoryConstraints);
205
            }
206
        }
207
    }
208
209
    /**
210 30
     * Returns the category constraint depending on the category conjunction configured in eventDemand
211
     *
212 30
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
213 2
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand
214 2
     * @param array $categoryConstraints
215 30
     * @return mixed
216
     */
217
    public function getCategoryConstraint($query, $eventDemand, $categoryConstraints)
218
    {
219
        switch (strtolower($eventDemand->getCategoryConjunction())) {
220
            case 'and':
221
                $constraint = $query->logicalAnd($categoryConstraints);
222
                break;
223
            case 'notor':
224
                $constraint = $query->logicalNot($query->logicalOr($categoryConstraints));
225
                break;
226 30
            case 'notand':
227
                $constraint = $query->logicalNot($query->logicalAnd($categoryConstraints));
228 30
                break;
229 2
            case 'or':
230 2
            default:
231 30
                $constraint = $query->logicalOr($categoryConstraints);
232
        }
233
234
        return $constraint;
235
    }
236
237
    /**
238
     * Sets the location constraint to the given constraints array
239
     *
240
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
241
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
242 30
     * @param array $constraints Constraints
243
     *
244
     * @return void
245 30
     */
246 1
    protected function setLocationConstraint($query, $eventDemand, &$constraints)
247 1
    {
248
        if ($eventDemand->getLocation() !== null && $eventDemand->getLocation() != '') {
249
            $constraints[] = $query->equals('location', $eventDemand->getLocation());
250 30
        }
251 1
    }
252 1
253 30
    /**
254
     * Sets the location.city constraint to the given constraints array
255
     *
256
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
257
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
258
     * @param array $constraints Constraints
259
     *
260
     * @return void
261
     */
262
    protected function setLocationCityConstraint($query, $eventDemand, &$constraints)
263
    {
264 30
        if ($eventDemand->getLocationCity() !== null && $eventDemand->getLocationCity() != '') {
265
            $constraints[] = $query->equals('location.city', $eventDemand->getLocationCity());
266 30
        }
267 30
    }
268 3
269 30
    /**
270 1
     * Sets the location.country constraint to the given constraints array
271 1
     *
272
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
273 1
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
274
     * @param array $constraints Constraints
275
     *
276
     * @return void
277 1
     */
278 1
    protected function setLocationCountryConstraint($query, $eventDemand, &$constraints)
279 1
    {
280 1
        if ($eventDemand->getLocationCountry() !== null && $eventDemand->getLocationCountry() != '') {
281 1
            $constraints[] = $query->equals('location.country', $eventDemand->getLocationCountry());
282 1
        }
283
    }
284 1
285 1
    /**
286 1
     * Sets the speaker constraint to the given constraints array
287 1
     *
288 30
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
289
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
290
     * @param array $constraints Constraints
291
     *
292
     * @return void
293
     */
294
    protected function setSpeakerConstraint($query, $eventDemand, &$constraints)
295
    {
296
        if ($eventDemand->getSpeaker() !== null && $eventDemand->getSpeaker() != '') {
297
            $constraints[] = $query->contains('speaker', $eventDemand->getSpeaker());
298
        }
299 30
    }
300
301 30
    /**
302 2
     * Sets the organisator constraint to the given constraints array
303 2
     *
304 30
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
305
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
306
     * @param array $constraints Constraints
307
     *
308
     * @return void
309
     */
310
    protected function setOrganisatorConstraint($query, $eventDemand, &$constraints)
311
    {
312
        if ($eventDemand->getOrganisator() !== null && $eventDemand->getOrganisator() != '') {
313
            $constraints[] = $query->equals('organisator', $eventDemand->getOrganisator());
314
        }
315
    }
316
317
    /**
318
     * Sets the start- and enddate constraint to the given constraints array
319
     *
320
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
321
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
322
     * @param array $constraints Constraints
323
     *
324
     * @return void
325
     */
326
    protected function setStartEndDateConstraint($query, $eventDemand, &$constraints)
327
    {
328
        if ($eventDemand->getSearchDemand() && $eventDemand->getSearchDemand()->getStartDate() !== null &&
329
            $eventDemand->getSearchDemand()->getEndDate() !== null
330
        ) {
331
            /* StartDate and EndDate  - Search for events between two given dates */
332
            $begin = $eventDemand->getSearchDemand()->getStartDate();
333
            $end = $eventDemand->getSearchDemand()->getEndDate();
334
            $constraints[] = $query->logicalOr([
335
                $query->between('startdate', $begin, $end),
336
                $query->between('enddate', $begin, $end),
337
                $query->logicalAnd([
338
                    $query->greaterThanOrEqual('enddate', $begin),
339
                    $query->lessThanOrEqual('startdate', $begin)
340
                ])
341
            ]);
342
        } elseif ($eventDemand->getSearchDemand() && $eventDemand->getSearchDemand()->getStartDate() !== null) {
343
            /* StartDate - Search for events beginning at a given date */
344
            $constraints[] = $query->greaterThanOrEqual('startdate', $eventDemand->getSearchDemand()->getStartDate());
345
        } elseif ($eventDemand->getSearchDemand() && $eventDemand->getSearchDemand()->getEndDate() !== null) {
346
            /* EndDate - Search for events ending on a given date */
347
            $constraints[] = $query->lessThanOrEqual('enddate', $eventDemand->getSearchDemand()->getEndDate());
348
        }
349
    }
350
351
    /**
352
     * Sets the search constraint to the given constraints array
353
     *
354
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
355
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
356
     * @param array $constraints Constraints
357
     *
358
     * @return void
359
     */
360
    protected function setSearchConstraint($query, $eventDemand, &$constraints)
361
    {
362
        if ($eventDemand->getSearchDemand() &&
363
            $eventDemand->getSearchDemand()->getSearch() !== null &&
364
            $eventDemand->getSearchDemand()->getSearch() !== ''
365
        ) {
366
            $searchFields = GeneralUtility::trimExplode(',', $eventDemand->getSearchDemand()->getFields(), true);
367
            $searchConstraints = [];
368
369
            if (count($searchFields) === 0) {
370
                throw new \UnexpectedValueException('No search fields defined', 1318497755);
371
            }
372
373
            $searchSubject = $eventDemand->getSearchDemand()->getSearch();
374
            foreach ($searchFields as $field) {
375
                if (!empty($searchSubject)) {
376
                    $searchConstraints[] = $query->like($field, '%' . addcslashes($searchSubject, '_%') . '%', false);
0 ignored issues
show
Unused Code introduced by
The call to QueryInterface::like() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
377
                }
378
            }
379
380
            if (count($searchConstraints)) {
381
                $constraints[] = $query->logicalOr($searchConstraints);
382
            }
383
        }
384
    }
385
386
    /**
387
     * Sets the topEvent constraint to the given constraints array
388
     *
389
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query Query
390
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand EventDemand
391
     * @param array $constraints Constraints
392
     *
393
     * @return void
394
     */
395
    protected function setTopEventConstraint($query, $eventDemand, &$constraints)
396
    {
397
        if ($eventDemand->getTopEventRestriction() > 0) {
398
            $constraints[] = $query->equals('topEvent', (bool)($eventDemand->getTopEventRestriction() - 1));
399
        }
400
    }
401
402
    /**
403
     * Sets the restriction for year, year/month or year/month/day to the given constraints array
404
     *
405
     * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
406
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Dto\EventDemand $eventDemand
407
     * @param array $constraints
408
     *
409
     * @return void
410
     */
411
    protected function setYearMonthDayRestriction($query, $eventDemand, &$constraints)
412
    {
413
        if ($eventDemand->getYear() > 0) {
414
            if ($eventDemand->getMonth() > 0) {
415
                if ($eventDemand->getDay() > 0) {
416
                    $begin = mktime(0, 0, 0, $eventDemand->getMonth(), $eventDemand->getDay(), $eventDemand->getYear());
417
                    $end = mktime(23, 59, 59, $eventDemand->getMonth(), $eventDemand->getDay(), $eventDemand->getYear());
418
                } else {
419
                    $begin = mktime(0, 0, 0, $eventDemand->getMonth(), 1, $eventDemand->getYear());
420
                    $end = mktime(23, 59, 59, ($eventDemand->getMonth() + 1), 0, $eventDemand->getYear());
421
                }
422
            } else {
423
                $begin = mktime(0, 0, 0, 1, 1, $eventDemand->getYear());
424
                $end = mktime(23, 59, 59, 12, 31, $eventDemand->getYear());
425
            }
426
            $constraints[] = $query->logicalOr([
427
                $query->between('startdate', $begin, $end),
428
                $query->between('enddate', $begin, $end),
429
                $query->logicalAnd([
430
                    $query->greaterThanOrEqual('enddate', $begin),
431
                    $query->lessThanOrEqual('startdate', $begin)
432
                ])
433
            ]);
434
        }
435
    }
436
}
437