Completed
Push — typo3-10-compatibility ( b4f2e1...42d8ec )
by Torben
03:17
created

NotificationService::sendUserMessage()   C

Complexity

Conditions 9
Paths 6

Size

Total Lines 92

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 92
rs 6.6189
c 0
b 0
f 0
cc 9
nc 6
nop 5

How to fix   Long Method   

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\Event\AfterAdminMessageSentEvent;
12
use DERHANSEN\SfEventMgt\Event\AfterUserMessageSentEvent;
13
use DERHANSEN\SfEventMgt\Event\ModifyUserMessageAttachmentsEvent;
14
use DERHANSEN\SfEventMgt\Event\ModifyUserMessageSenderEvent;
15
use DERHANSEN\SfEventMgt\Utility\MessageRecipient;
16
use DERHANSEN\SfEventMgt\Utility\MessageType;
17
use Psr\EventDispatcher\EventDispatcherInterface;
18
use TYPO3\CMS\Core\Utility\GeneralUtility;
19
20
/**
21
 * NotificationService
22
 *
23
 * @author Torben Hansen <[email protected]>
24
 */
25
class NotificationService
26
{
27
    /**
28
     * The object manager
29
     *
30
     * @var \TYPO3\CMS\Extbase\Object\ObjectManager
31
     */
32
    protected $objectManager;
33
34
    /**
35
     * Registration repository
36
     *
37
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
38
     */
39
    protected $registrationRepository = null;
40
41
    /**
42
     * Email Service
43
     *
44
     * @var \DERHANSEN\SfEventMgt\Service\EmailService
45
     */
46
    protected $emailService;
47
48
    /**
49
     * Hash Service
50
     *
51
     * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
52
     */
53
    protected $hashService;
54
55
    /**
56
     * FluidStandaloneService
57
     *
58
     * @var \DERHANSEN\SfEventMgt\Service\FluidStandaloneService
59
     */
60
    protected $fluidStandaloneService;
61
62
    /**
63
     * CustomNotificationLogRepository
64
     *
65
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository
66
     */
67
    protected $customNotificationLogRepository = null;
68
69
    /**
70
     * AttachmentService
71
     *
72
     * @var \DERHANSEN\SfEventMgt\Service\Notification\AttachmentService
73
     */
74
    protected $attachmentService;
75
76
    /**
77
     * @var EventDispatcherInterface
78
     */
79
    protected $eventDispatcher;
80
81
    /**
82
     * DI for $attachmentService
83
     *
84
     * @param Notification\AttachmentService $attachmentService
85
     */
86
    public function injectAttachmentService(
87
        \DERHANSEN\SfEventMgt\Service\Notification\AttachmentService $attachmentService
88
    ) {
89
        $this->attachmentService = $attachmentService;
90
    }
91
92
    /**
93
     * DI for $customNotificationLogRepository
94
     *
95
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
96
     */
97
    public function injectCustomNotificationLogRepository(
98
        \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
99
    ) {
100
        $this->customNotificationLogRepository = $customNotificationLogRepository;
101
    }
102
103
    /**
104
     * DI for $emailService
105
     *
106
     * @param EmailService $emailService
107
     */
108
    public function injectEmailService(\DERHANSEN\SfEventMgt\Service\EmailService $emailService)
109
    {
110
        $this->emailService = $emailService;
111
    }
112
113
    /**
114
     * DI for $fluidStandaloneService
115
     *
116
     * @param FluidStandaloneService $fluidStandaloneService
117
     */
118
    public function injectFluidStandaloneService(
119
        \DERHANSEN\SfEventMgt\Service\FluidStandaloneService $fluidStandaloneService
120
    ) {
121
        $this->fluidStandaloneService = $fluidStandaloneService;
122
    }
123
124
    /**
125
     * DI for $hashService
126
     *
127
     * @param \TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService
128
     */
129
    public function injectHashService(\TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService)
130
    {
131
        $this->hashService = $hashService;
132
    }
133
134
    /**
135
     * DI for $objectManager
136
     *
137
     * @param \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager
138
     */
139
    public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManager $objectManager)
140
    {
141
        $this->objectManager = $objectManager;
142
    }
143
144
    /**
145
     * DI for $registrationRepository
146
     *
147
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
148
     */
149
    public function injectRegistrationRepository(
150
        \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
151
    ) {
152
        $this->registrationRepository = $registrationRepository;
153
    }
154
155
    /**
156
     * @param EventDispatcherInterface $eventDispatcher
157
     */
158
    public function injectEventDispatcher(EventDispatcherInterface $eventDispatcher)
159
    {
160
        $this->eventDispatcher = $eventDispatcher;
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 Event
168
     * @param string $customNotification CustomNotification
169
     * @param array $settings Settings
170
     *
171
     * @return int Number of notifications sent
172
     */
173
    public function sendCustomNotification($event, $customNotification, $settings)
174
    {
175
        if ($this->cantSendCustomNotification($event, $settings, $customNotification)) {
176
            return 0;
177
        }
178
        $count = 0;
179
180
        $constraints = $settings['notification']['customNotifications'][$customNotification]['constraints'];
181
        $registrations = $this->registrationRepository->findNotificationRegistrations($event, $constraints);
182
        foreach ($registrations as $registration) {
183
            /** @var \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration */
184
            if ($registration->isConfirmed() && !$registration->isIgnoreNotifications()) {
185
                $result = $this->sendUserMessage(
186
                    $event,
187
                    $registration,
188
                    $settings,
189
                    MessageType::CUSTOM_NOTIFICATION,
190
                    $customNotification
191
                );
192
                if ($result) {
193
                    $count += 1;
194
                }
195
            }
196
        }
197
198
        return $count;
199
    }
200
201
    /**
202
     * Returns true if conditions are not met to send a custom notification
203
     *
204
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
205
     * @param array $settings
206
     * @param string $customNotification
207
     *
208
     * @return bool
209
     */
210
    protected function cantSendCustomNotification($event, $settings, $customNotification)
211
    {
212
        return is_null($event) || $customNotification == '' || $settings == '' || !is_array($settings);
213
    }
214
215
    /**
216
     * Adds a logentry to the custom notification log
217
     *
218
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
219
     * @param string $details Details
220
     * @param int $emailsSent E-Mails sent
221
     *
222
     * @return void
223
     */
224
    public function createCustomNotificationLogentry($event, $details, $emailsSent)
225
    {
226
        $notificationlogEntry = new \DERHANSEN\SfEventMgt\Domain\Model\CustomNotificationLog();
227
        $notificationlogEntry->setEvent($event);
228
        $notificationlogEntry->setDetails($details);
229
        $notificationlogEntry->setEmailsSent($emailsSent);
230
        $notificationlogEntry->setCruserId($GLOBALS['BE_USER']->user['uid']);
231
        $this->customNotificationLogRepository->add($notificationlogEntry);
232
    }
233
234
    /**
235
     * Sends a message to the user based on the given type
236
     *
237
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
238
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
239
     * @param array $settings Settings
240
     * @param int $type Type
241
     * @param string $customNotification CustomNotification
242
     *
243
     * @return bool TRUE if successful, else FALSE
244
     */
245
    public function sendUserMessage($event, $registration, $settings, $type, $customNotification = '')
246
    {
247
        list($template, $subject) = $this->getUserMessageTemplateSubject($settings, $type, $customNotification);
248
249
        if (is_null($event) || is_null($registration) || is_null($type) || !is_array($settings) ||
250
            (substr($template, -5) != '.html')
251
        ) {
252
            return false;
253
        }
254
255
        if (!$registration->isIgnoreNotifications()) {
256
            $body = $this->getNotificationBody($event, $registration, $template, $settings);
257
            $subject = $this->fluidStandaloneService->parseStringFluid(
258
                $subject,
259
                [
260
                    'event' => $event,
261
                    'registration' => $registration
262
                ]
263
            );
264
            $attachments = $this->attachmentService->getAttachments(
265
                $settings,
266
                $registration,
267
                $type,
268
                MessageRecipient::USER
269
            );
270
271
            // Get iCal attachment if configured
272
            $iCalAttachment = $this->attachmentService->getICalAttachment(
273
                $settings,
274
                $registration,
275
                $type,
276
                MessageRecipient::USER
277
            );
278
279
            if ($iCalAttachment !== '') {
280
                $attachments[] = $iCalAttachment;
281
            }
282
283
            $modifyUserMessageSenderEvent = new ModifyUserMessageSenderEvent(
284
                $settings['notification']['senderName'] ?? '',
285
                $settings['notification']['senderEmail'] ?? '',
286
                $settings['notification']['replyToEmail'] ?? '',
287
                $registration,
288
                $type,
289
                $this
290
            );
291
            $this->eventDispatcher->dispatch($modifyUserMessageSenderEvent);
0 ignored issues
show
Documentation introduced by
$modifyUserMessageSenderEvent is of type object<DERHANSEN\SfEvent...UserMessageSenderEvent>, but the function expects a object<Psr\EventDispatcher\object>.

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...
292
            $senderName = $modifyUserMessageSenderEvent->getSenderName();
293
            $senderEmail = $modifyUserMessageSenderEvent->getSenderEmail();
294
            $replyToEmail = $modifyUserMessageSenderEvent->getReplyToEmail();
295
296
            $modifyUserAttachmentsEvent = new ModifyUserMessageAttachmentsEvent(
297
                $attachments,
298
                $registration,
299
                $type,
300
                $this
301
            );
302
            $this->eventDispatcher->dispatch($modifyUserMessageSenderEvent);
0 ignored issues
show
Documentation introduced by
$modifyUserMessageSenderEvent is of type object<DERHANSEN\SfEvent...UserMessageSenderEvent>, but the function expects a object<Psr\EventDispatcher\object>.

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...
303
            $attachments = $modifyUserAttachmentsEvent->getAttachments();
304
305
            $result = $this->emailService->sendEmailMessage(
306
                $senderEmail,
307
                $registration->getEmail(),
308
                $subject,
309
                $body,
310
                $senderName,
311
                $attachments,
312
                $replyToEmail
313
            );
314
315
            $afterUserMessageSentEvent = new AfterUserMessageSentEvent(
316
                $registration,
317
                $body,
318
                $subject,
319
                $attachments,
320
                $senderName,
321
                $senderEmail,
322
                $replyToEmail,
323
                $this
324
            );
325
            $this->eventDispatcher->dispatch($afterUserMessageSentEvent);
0 ignored issues
show
Documentation introduced by
$afterUserMessageSentEvent is of type object<DERHANSEN\SfEvent...erUserMessageSentEvent>, but the function expects a object<Psr\EventDispatcher\object>.

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...
326
327
            // Cleanup iCal attachment if available
328
            if ($iCalAttachment !== '') {
329
                \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($iCalAttachment);
330
            }
331
332
            return $result;
333
        }
334
335
        return false;
336
    }
337
338
    /**
339
     * Returns an array with template and subject for the user message
340
     *
341
     * @param array $settings
342
     * @param int $type Type
343
     * @param string $customNotification
344
     * @return array
345
     */
346
    protected function getUserMessageTemplateSubject($settings, $type, $customNotification)
347
    {
348
        $template = 'Notification/User/RegistrationNew.html';
349
        $subject = $settings['notification']['registrationNew']['userSubject'];
350
        switch ($type) {
351
            case MessageType::REGISTRATION_WAITLIST_NEW:
352
                $template = 'Notification/User/RegistrationWaitlistNew.html';
353
                $subject = $settings['notification']['registrationWaitlistNew']['userSubject'];
354
                break;
355
            case MessageType::REGISTRATION_CONFIRMED:
356
                $template = 'Notification/User/RegistrationConfirmed.html';
357
                $subject = $settings['notification']['registrationConfirmed']['userSubject'];
358
                break;
359
            case MessageType::REGISTRATION_WAITLIST_CONFIRMED:
360
                $template = 'Notification/User/RegistrationWaitlistConfirmed.html';
361
                $subject = $settings['notification']['registrationWaitlistConfirmed']['userSubject'];
362
                break;
363
            case MessageType::REGISTRATION_CANCELLED:
364
                $template = 'Notification/User/RegistrationCancelled.html';
365
                $subject = $settings['notification']['registrationCancelled']['userSubject'];
366
                break;
367
            case MessageType::CUSTOM_NOTIFICATION:
368
                $template = 'Notification/User/Custom/' . $settings['notification']['customNotifications'][$customNotification]['template'];
369
                $subject = $settings['notification']['customNotifications'][$customNotification]['subject'];
370
                break;
371
            case MessageType::REGISTRATION_NEW:
372
            default:
373
        }
374
375
        return [
376
            $template,
377
            $subject
378
        ];
379
    }
380
381
    /**
382
     * Sends a message to the admin based on the given type
383
     *
384
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
385
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
386
     * @param array $settings Settings
387
     * @param int $type Type
388
     *
389
     * @return bool TRUE if successful, else FALSE
390
     */
391
    public function sendAdminMessage($event, $registration, $settings, $type)
392
    {
393
        list($template, $subject) = $this->getAdminMessageTemplateSubject($settings, $type);
394
395
        if (is_null($event) || is_null($registration || !is_array($settings)) ||
396
            ($event->getNotifyAdmin() === false && $event->getNotifyOrganisator() === false)
397
        ) {
398
            return false;
399
        }
400
401
        $allEmailsSent = true;
402
        $body = $this->getNotificationBody($event, $registration, $template, $settings);
403
        $subject = $this->fluidStandaloneService->parseStringFluid(
404
            $subject,
405
            [
406
                'event' => $event,
407
                'registration' => $registration
408
            ]
409
        );
410
        $attachments = $this->attachmentService->getAttachments(
411
            $settings,
412
            $registration,
413
            $type,
414
            MessageRecipient::ADMIN
415
        );
416
417
        $senderName = $settings['notification']['senderName'];
418
        $senderEmail = $settings['notification']['senderEmail'];
419
        if ((bool)$settings['notification']['registrationDataAsSenderForAdminEmails']) {
420
            $senderName = $registration->getFullname();
421
            $senderEmail = $registration->getEmail();
422
        }
423
424
        if ($event->getNotifyAdmin()) {
425
            $adminEmailArr = GeneralUtility::trimExplode(',', $settings['notification']['adminEmail'], true);
426
            foreach ($adminEmailArr as $adminEmail) {
427
                $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
428
                    $senderEmail,
429
                    $adminEmail,
430
                    $subject,
431
                    $body,
432
                    $senderName,
433
                    $attachments
434
                );
435
            }
436
        }
437
438
        if ($event->getNotifyOrganisator() && $event->getOrganisator()) {
439
            $allEmailsSent = $allEmailsSent && $this->emailService->sendEmailMessage(
440
                $senderEmail,
441
                $event->getOrganisator()->getEmail(),
442
                $subject,
443
                $body,
444
                $senderName,
445
                $attachments
446
            );
447
        }
448
449
        $afterAdminMessageSentEvent = new AfterAdminMessageSentEvent(
450
            $registration,
451
            $body,
452
            $subject,
453
            $attachments,
454
            $senderName,
455
            $senderEmail,
456
            $this
457
        );
458
        $this->eventDispatcher->dispatch($afterAdminMessageSentEvent);
0 ignored issues
show
Documentation introduced by
$afterAdminMessageSentEvent is of type object<DERHANSEN\SfEvent...rAdminMessageSentEvent>, but the function expects a object<Psr\EventDispatcher\object>.

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...
459
460
        return $allEmailsSent;
461
    }
462
463
    /**
464
     * Returns an array with template and subject for the admin message
465
     *
466
     * @param array $settings
467
     * @param int $type Type
468
     * @return array
469
     */
470
    protected function getAdminMessageTemplateSubject($settings, $type)
471
    {
472
        $template = 'Notification/Admin/RegistrationNew.html';
473
        $subject = $settings['notification']['registrationNew']['adminSubject'];
474
        switch ($type) {
475
            case MessageType::REGISTRATION_WAITLIST_NEW:
476
                $template = 'Notification/Admin/RegistrationWaitlistNew.html';
477
                $subject = $settings['notification']['registrationWaitlistNew']['adminSubject'];
478
                break;
479
            case MessageType::REGISTRATION_CONFIRMED:
480
                $template = 'Notification/Admin/RegistrationConfirmed.html';
481
                $subject = $settings['notification']['registrationConfirmed']['adminSubject'];
482
                break;
483
            case MessageType::REGISTRATION_WAITLIST_CONFIRMED:
484
                $template = 'Notification/Admin/RegistrationWaitlistConfirmed.html';
485
                $subject = $settings['notification']['registrationWaitlistConfirmed']['adminSubject'];
486
                break;
487
            case MessageType::REGISTRATION_CANCELLED:
488
                $template = 'Notification/Admin/RegistrationCancelled.html';
489
                $subject = $settings['notification']['registrationCancelled']['adminSubject'];
490
                break;
491
            case MessageType::REGISTRATION_NEW:
492
            default:
493
        }
494
495
        return [
496
            $template,
497
            $subject
498
        ];
499
    }
500
501
    /**
502
     * Returns the rendered HTML for the given template
503
     *
504
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
505
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
506
     * @param string $template Template
507
     * @param array $settings Settings
508
     *
509
     * @return string
510
     */
511
    protected function getNotificationBody($event, $registration, $template, $settings)
512
    {
513
        if (TYPO3_MODE === 'BE' && $registration->getLanguage() !== '') {
514
            // Temporary set Language of current BE user to given language
515
            $GLOBALS['BE_USER']->uc['lang'] = $registration->getLanguage();
516
        }
517
        $variables = [
518
            'event' => $event,
519
            'registration' => $registration,
520
            'settings' => $settings,
521
            'hmac' => $this->hashService->generateHmac('reg-' . $registration->getUid()),
522
            'reghmac' => $this->hashService->appendHmac((string)$registration->getUid())
523
        ];
524
525
        return $this->fluidStandaloneService->renderTemplate($template, $variables);
526
    }
527
}
528