Completed
Push — 4.x ( a36c9f...e4382f )
by Torben
02:26
created

NotificationService::sendUserMessage()   C

Complexity

Conditions 10
Paths 6

Size

Total Lines 88

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 88
rs 6.3951
c 0
b 0
f 0
cc 10
nc 6
nop 5

How to fix   Long Method    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
namespace DERHANSEN\SfEventMgt\Service;
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\CustomNotification;
12
use DERHANSEN\SfEventMgt\Domain\Model\Event;
13
use DERHANSEN\SfEventMgt\Utility\MessageRecipient;
14
use DERHANSEN\SfEventMgt\Utility\MessageType;
15
use TYPO3\CMS\Core\Utility\GeneralUtility;
16
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
17
18
/**
19
 * NotificationService
20
 *
21
 * @author Torben Hansen <[email protected]>
22
 */
23
class NotificationService
24
{
25
    /**
26
     * The object manager
27
     *
28
     * @var \TYPO3\CMS\Extbase\Object\ObjectManager
29
     */
30
    protected $objectManager;
31
32
    /**
33
     * Registration repository
34
     *
35
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
36
     */
37
    protected $registrationRepository = null;
38
39
    /**
40
     * Email Service
41
     *
42
     * @var \DERHANSEN\SfEventMgt\Service\EmailService
43
     */
44
    protected $emailService;
45
46
    /**
47
     * Hash Service
48
     *
49
     * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
50
     */
51
    protected $hashService;
52
53
    /**
54
     * FluidStandaloneService
55
     *
56
     * @var \DERHANSEN\SfEventMgt\Service\FluidStandaloneService
57
     */
58
    protected $fluidStandaloneService;
59
60
    /**
61
     * CustomNotificationLogRepository
62
     *
63
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository
64
     */
65
    protected $customNotificationLogRepository = null;
66
67
    /**
68
     * AttachmentService
69
     *
70
     * @var \DERHANSEN\SfEventMgt\Service\Notification\AttachmentService
71
     */
72
    protected $attachmentService;
73
74
    /**
75
     * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
76
     */
77
    protected $signalSlotDispatcher = null;
78
79
    /**
80
     * DI for $attachmentService
81
     *
82
     * @param Notification\AttachmentService $attachmentService
83
     */
84
    public function injectAttachmentService(
85
        \DERHANSEN\SfEventMgt\Service\Notification\AttachmentService $attachmentService
86
    ) {
87
        $this->attachmentService = $attachmentService;
88
    }
89
90
    /**
91
     * DI for $customNotificationLogRepository
92
     *
93
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
94
     */
95
    public function injectCustomNotificationLogRepository(
96
        \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
97
    ) {
98
        $this->customNotificationLogRepository = $customNotificationLogRepository;
99
    }
100
101
    /**
102
     * DI for $emailService
103
     *
104
     * @param EmailService $emailService
105
     */
106
    public function injectEmailService(\DERHANSEN\SfEventMgt\Service\EmailService $emailService)
107
    {
108
        $this->emailService = $emailService;
109
    }
110
111
    /**
112
     * DI for $fluidStandaloneService
113
     *
114
     * @param FluidStandaloneService $fluidStandaloneService
115
     */
116
    public function injectFluidStandaloneService(
117
        \DERHANSEN\SfEventMgt\Service\FluidStandaloneService $fluidStandaloneService
118
    ) {
119
        $this->fluidStandaloneService = $fluidStandaloneService;
120
    }
121
122
    /**
123
     * DI for $hashService
124
     *
125
     * @param \TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService
126
     */
127
    public function injectHashService(\TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService)
128
    {
129
        $this->hashService = $hashService;
130
    }
131
132
    /**
133
     * DI for $objectManager
134
     *
135
     * @param \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager
136
     */
137
    public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManager $objectManager)
138
    {
139
        $this->objectManager = $objectManager;
140
    }
141
142
    /**
143
     * DI for $registrationRepository
144
     *
145
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
146
     */
147
    public function injectRegistrationRepository(
148
        \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
149
    ) {
150
        $this->registrationRepository = $registrationRepository;
151
    }
152
153
    /**
154
     * DI for $signalSlotDispatcher
155
     *
156
     * @param Dispatcher $signalSlotDispatcher
157
     */
158
    public function injectSignalSlotDispatcher(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher $signalSlotDispatcher)
159
    {
160
        $this->signalSlotDispatcher = $signalSlotDispatcher;
161
    }
162
163
    /**
164
     * Sends a custom notification defined by the given customNotification key
165
     * to all confirmed users of the event
166
     *
167
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
168
     * @param CustomNotification $customNotification
169
     * @param array $settings Settings
170
     *
171
     * @return int Number of notifications sent
172
     */
173
    public function sendCustomNotification(Event $event, CustomNotification $customNotification, array $settings = [])
174
    {
175
        if ($this->cantSendCustomNotification($event, $settings, $customNotification)) {
176
            return 0;
177
        }
178
        $count = 0;
179
180
        $customNotificationSettings = $settings['notification']['customNotifications'];
181
        $constraints = $customNotificationSettings[$customNotification->getTemplate()]['constraints'] ?? [];
182
        $registrations = $this->registrationRepository->findNotificationRegistrations(
183
            $event,
184
            $customNotification,
185
            $constraints
186
        );
187
188
        foreach ($registrations as $registration) {
189
            /** @var \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration */
190
            if ($registration->isConfirmed() && !$registration->isIgnoreNotifications()) {
191
                $result = $this->sendUserMessage(
192
                    $event,
193
                    $registration,
194
                    $settings,
195
                    MessageType::CUSTOM_NOTIFICATION,
196
                    $customNotification
197
                );
198
                if ($result) {
199
                    $count += 1;
200
                }
201
            }
202
        }
203
204
        return $count;
205
    }
206
207
    /**
208
     * Returns true if conditions are not met to send a custom notification
209
     *
210
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
211
     * @param array $settings
212
     * @param CustomNotification $customNotification
213
     *
214
     * @return bool
215
     */
216
    protected function cantSendCustomNotification($event, $settings, $customNotification)
217
    {
218
        return is_null($event) || $customNotification === null || $customNotification->getTemplate() === '' ||
219
            empty($settings);
220
    }
221
222
    /**
223
     * Adds a logentry to the custom notification log
224
     *
225
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
226
     * @param string $details Details
227
     * @param int $emailsSent E-Mails sent
228
     *
229
     * @return void
230
     */
231
    public function createCustomNotificationLogentry($event, $details, $emailsSent)
232
    {
233
        $notificationlogEntry = new \DERHANSEN\SfEventMgt\Domain\Model\CustomNotificationLog();
234
        $notificationlogEntry->setEvent($event);
235
        $notificationlogEntry->setDetails($details);
236
        $notificationlogEntry->setEmailsSent($emailsSent);
237
        $notificationlogEntry->setCruserId($GLOBALS['BE_USER']->user['uid']);
238
        $this->customNotificationLogRepository->add($notificationlogEntry);
239
    }
240
241
    /**
242
     * Sends a message to the user based on the given type
243
     *
244
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
245
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
246
     * @param array $settings Settings
247
     * @param int $type Type
248
     * @param CustomNotification $customNotification
249
     *
250
     * @return bool TRUE if successful, else FALSE
251
     */
252
    public function sendUserMessage($event, $registration, $settings, $type, $customNotification = null)
253
    {
254
        list($template, $subject) = $this->getUserMessageTemplateSubject(
255
            $settings,
256
            $type,
257
            $customNotification
258
        );
259
260
        if (is_null($event) || is_null($registration) || is_null($type) || !is_array($settings) ||
261
            (substr($template, -5) != '.html') || (bool)$settings['notification']['disabled']
262
        ) {
263
            return false;
264
        }
265
266
        $additionalBodyVariables = [
267
            'customNotification' => $customNotification
268
        ];
269
270
        if (!$registration->isIgnoreNotifications()) {
271
            $body = $this->getNotificationBody($event, $registration, $template, $settings, $additionalBodyVariables);
272
            $subject = $this->fluidStandaloneService->parseStringFluid(
273
                $subject,
274
                [
275
                    'event' => $event,
276
                    'registration' => $registration
277
                ]
278
            );
279
            $attachments = $this->attachmentService->getAttachments(
280
                $settings,
281
                $registration,
282
                $type,
283
                MessageRecipient::USER
284
            );
285
286
            // Get iCal attachment if configured
287
            $iCalAttachment = $this->attachmentService->getICalAttachment(
288
                $settings,
289
                $registration,
290
                $type,
291
                MessageRecipient::USER
292
            );
293
294
            if ($iCalAttachment !== '') {
295
                $attachments[] = $iCalAttachment;
296
            }
297
298
            $senderName = $settings['notification']['senderName'];
299
            $senderEmail = $settings['notification']['senderEmail'];
300
            $replyToEmail = $settings['notification']['replyToEmail'];
301
302
            $this->signalSlotDispatcher->dispatch(
303
                __CLASS__,
304
                __FUNCTION__ . 'CustomSenderData',
305
                [&$senderName, &$senderEmail, &$replyToEmail, $registration, $type, $this]
306
            );
307
308
            $this->signalSlotDispatcher->dispatch(
309
                __CLASS__,
310
                __FUNCTION__ . 'CustomAttachmentData',
311
                [&$attachments, $registration, $type, $this]
312
            );
313
314
            $result = $this->emailService->sendEmailMessage(
315
                $senderEmail,
316
                $registration->getEmail(),
317
                $subject,
318
                $body,
319
                $senderName,
320
                $attachments,
321
                $replyToEmail
322
            );
323
324
            $this->signalSlotDispatcher->dispatch(
325
                __CLASS__,
326
                __FUNCTION__ . 'AfterNotificationSent',
327
                [$registration, $body, $subject, $attachments, $senderName, $senderEmail, $replyToEmail, $this]
328
            );
329
330
            // Cleanup iCal attachment if available
331
            if ($iCalAttachment !== '') {
332
                \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($iCalAttachment);
333
            }
334
335
            return $result;
336
        }
337
338
        return false;
339
    }
340
341
    /**
342
     * Returns an array with template and subject for the user message
343
     *
344
     * @param array $settings
345
     * @param int $type Type
346
     * @param CustomNotification $customNotification
347
     * @return array
348
     */
349
    protected function getUserMessageTemplateSubject($settings, $type, $customNotification = null)
350
    {
351
        switch ($type) {
352
            case MessageType::REGISTRATION_NEW:
353
                $template = 'Notification/User/RegistrationNew.html';
354
                $subject = $settings['notification']['registrationNew']['userSubject'];
355
                break;
356
            case MessageType::REGISTRATION_WAITLIST_NEW:
357
                $template = 'Notification/User/RegistrationWaitlistNew.html';
358
                $subject = $settings['notification']['registrationWaitlistNew']['userSubject'];
359
                break;
360
            case MessageType::REGISTRATION_CONFIRMED:
361
                $template = 'Notification/User/RegistrationConfirmed.html';
362
                $subject = $settings['notification']['registrationConfirmed']['userSubject'];
363
                break;
364
            case MessageType::REGISTRATION_WAITLIST_CONFIRMED:
365
                $template = 'Notification/User/RegistrationWaitlistConfirmed.html';
366
                $subject = $settings['notification']['registrationWaitlistConfirmed']['userSubject'];
367
                break;
368
            case MessageType::REGISTRATION_CANCELLED:
369
                $template = 'Notification/User/RegistrationCancelled.html';
370
                $subject = $settings['notification']['registrationCancelled']['userSubject'];
371
                break;
372
            case MessageType::CUSTOM_NOTIFICATION && $customNotification:
373
                $customNotificationSettings = $settings['notification']['customNotifications'];
374
                $templateKey = $customNotification->getTemplate();
0 ignored issues
show
Bug introduced by
It seems like $customNotification 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...
375
                $template = 'Notification/User/Custom/' . $customNotificationSettings[$templateKey]['template'];
376
                $subject = $customNotificationSettings[$templateKey]['subject'];
377
                if ($customNotification->getOverwriteSubject() !== '') {
378
                    $subject = $customNotification->getOverwriteSubject();
379
                }
380
                break;
381
            default:
382
                $template = '';
383
                $subject = '';
384
        }
385
386
        return [
387
            $template,
388
            $subject
389
        ];
390
    }
391
392
    /**
393
     * Sends a message to the admin based on the given type
394
     *
395
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
396
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
397
     * @param array $settings Settings
398
     * @param int $type Type
399
     *
400
     * @return bool TRUE if successful, else FALSE
401
     */
402
    public function sendAdminMessage($event, $registration, $settings, $type)
403
    {
404
        list($template, $subject) = $this->getAdminMessageTemplateSubject($settings, $type);
405
406
        if (is_null($event) || is_null($registration || !is_array($settings)) ||
407
            ($event->getNotifyAdmin() === false && $event->getNotifyOrganisator() === false)
408
        ) {
409
            return false;
410
        }
411
412
        $allEmailsSent = true;
413
        $body = $this->getNotificationBody($event, $registration, $template, $settings);
414
        $subject = $this->fluidStandaloneService->parseStringFluid(
415
            $subject,
416
            [
417
                'event' => $event,
418
                'registration' => $registration
419
            ]
420
        );
421
        $attachments = $this->attachmentService->getAttachments(
422
            $settings,
423
            $registration,
424
            $type,
425
            MessageRecipient::ADMIN
426
        );
427
428
        $senderName = $settings['notification']['senderName'];
429
        $senderEmail = $settings['notification']['senderEmail'];
430
        if ((bool)$settings['notification']['registrationDataAsSenderForAdminEmails']) {
431
            $senderName = $registration->getFullname();
432
            $senderEmail = $registration->getEmail();
433
        }
434
435
        if ($event->getNotifyAdmin()) {
436
            $adminEmailArr = GeneralUtility::trimExplode(',', $settings['notification']['adminEmail'], true);
437
            foreach ($adminEmailArr as $adminEmail) {
438
                $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
439
                    $senderEmail,
440
                    $adminEmail,
441
                    $subject,
442
                    $body,
443
                    $senderName,
444
                    $attachments
445
                );
446
            }
447
        }
448
449
        if ($event->getNotifyOrganisator() && $event->getOrganisator()) {
450
            $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
451
                $senderEmail,
452
                $event->getOrganisator()->getEmail(),
453
                $subject,
454
                $body,
455
                $senderName,
456
                $attachments
457
            );
458
        }
459
460
        $this->signalSlotDispatcher->dispatch(
461
            __CLASS__,
462
            __FUNCTION__ . 'AfterNotificationSent',
463
            [$registration, $body, $subject, $attachments, $senderName, $senderEmail, $this]
464
        );
465
466
        return $allEmailsSent;
467
    }
468
469
    /**
470
     * Returns an array with template and subject for the admin message
471
     *
472
     * @param array $settings
473
     * @param int $type Type
474
     * @return array
475
     */
476
    protected function getAdminMessageTemplateSubject($settings, $type)
477
    {
478
        $template = 'Notification/Admin/RegistrationNew.html';
479
        $subject = $settings['notification']['registrationNew']['adminSubject'];
480
        switch ($type) {
481
            case MessageType::REGISTRATION_WAITLIST_NEW:
482
                $template = 'Notification/Admin/RegistrationWaitlistNew.html';
483
                $subject = $settings['notification']['registrationWaitlistNew']['adminSubject'];
484
                break;
485
            case MessageType::REGISTRATION_CONFIRMED:
486
                $template = 'Notification/Admin/RegistrationConfirmed.html';
487
                $subject = $settings['notification']['registrationConfirmed']['adminSubject'];
488
                break;
489
            case MessageType::REGISTRATION_WAITLIST_CONFIRMED:
490
                $template = 'Notification/Admin/RegistrationWaitlistConfirmed.html';
491
                $subject = $settings['notification']['registrationWaitlistConfirmed']['adminSubject'];
492
                break;
493
            case MessageType::REGISTRATION_CANCELLED:
494
                $template = 'Notification/Admin/RegistrationCancelled.html';
495
                $subject = $settings['notification']['registrationCancelled']['adminSubject'];
496
                break;
497
            case MessageType::REGISTRATION_NEW:
498
            default:
499
        }
500
501
        return [
502
            $template,
503
            $subject
504
        ];
505
    }
506
507
    /**
508
     * Returns the rendered HTML for the given template
509
     *
510
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
511
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
512
     * @param string $template Template
513
     * @param array $settings Settings
514
     * @param array $additionalBodyVariables
515
     * @return string
516
     */
517
    protected function getNotificationBody($event, $registration, $template, $settings, $additionalBodyVariables = [])
518
    {
519
        if (TYPO3_MODE === 'BE' && $registration->getLanguage() !== '') {
520
            // Temporary set Language of current BE user to given language
521
            $GLOBALS['BE_USER']->uc['lang'] = $registration->getLanguage();
522
        }
523
        $defaultVariables = [
524
            'event' => $event,
525
            'registration' => $registration,
526
            'settings' => $settings,
527
            'hmac' => $this->hashService->generateHmac('reg-' . $registration->getUid()),
528
            'reghmac' => $this->hashService->appendHmac((string)$registration->getUid())
529
        ];
530
        $variables = array_merge($additionalBodyVariables, $defaultVariables);
531
532
        return $this->fluidStandaloneService->renderTemplate($template, $variables);
533
    }
534
}
535