Completed
Push — master ( 70dfe1...a97a1c )
by Torben
04:18
created

NotificationService::sendUserMessage()   C

Complexity

Conditions 10
Paths 6

Size

Total Lines 92

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 10.0131

Importance

Changes 0
Metric Value
dl 0
loc 92
ccs 56
cts 59
cp 0.9492
rs 6.3078
c 0
b 0
f 0
cc 10
nc 6
nop 5
crap 10.0131

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
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\Service;
11
12
use DERHANSEN\SfEventMgt\Event\AfterAdminMessageSentEvent;
13
use DERHANSEN\SfEventMgt\Event\AfterUserMessageSentEvent;
14
use DERHANSEN\SfEventMgt\Event\ModifyUserMessageAttachmentsEvent;
15
use DERHANSEN\SfEventMgt\Event\ModifyUserMessageSenderEvent;
16
use DERHANSEN\SfEventMgt\Utility\MessageRecipient;
17
use DERHANSEN\SfEventMgt\Utility\MessageType;
18
use Psr\EventDispatcher\EventDispatcherInterface;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21
/**
22
 * NotificationService
23
 *
24
 * @author Torben Hansen <[email protected]>
25
 */
26
class NotificationService
27
{
28
    /**
29
     * The object manager
30
     *
31
     * @var \TYPO3\CMS\Extbase\Object\ObjectManager
32
     */
33
    protected $objectManager;
34
35
    /**
36
     * Registration repository
37
     *
38
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
39
     */
40
    protected $registrationRepository;
41
42
    /**
43
     * Email Service
44
     *
45
     * @var \DERHANSEN\SfEventMgt\Service\EmailService
46
     */
47
    protected $emailService;
48
49
    /**
50
     * Hash Service
51
     *
52
     * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
53
     */
54
    protected $hashService;
55
56
    /**
57
     * FluidStandaloneService
58
     *
59
     * @var \DERHANSEN\SfEventMgt\Service\FluidStandaloneService
60
     */
61
    protected $fluidStandaloneService;
62
63
    /**
64
     * CustomNotificationLogRepository
65
     *
66
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository
67
     */
68
    protected $customNotificationLogRepository;
69
70
    /**
71
     * AttachmentService
72
     *
73
     * @var \DERHANSEN\SfEventMgt\Service\Notification\AttachmentService
74
     */
75
    protected $attachmentService;
76
77
    /**
78
     * @var EventDispatcherInterface
79
     */
80
    protected $eventDispatcher;
81
82
    /**
83
     * DI for $attachmentService
84
     *
85
     * @param Notification\AttachmentService $attachmentService
86
     */
87
    public function injectAttachmentService(
88
        \DERHANSEN\SfEventMgt\Service\Notification\AttachmentService $attachmentService
89
    ) {
90
        $this->attachmentService = $attachmentService;
91
    }
92
93
    /**
94
     * DI for $customNotificationLogRepository
95 8
     *
96
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
97 8
     */
98 2
    public function injectCustomNotificationLogRepository(
99
        \DERHANSEN\SfEventMgt\Domain\Repository\CustomNotificationLogRepository $customNotificationLogRepository
100 6
    ) {
101
        $this->customNotificationLogRepository = $customNotificationLogRepository;
102 6
    }
103 6
104 6
    /**
105
     * DI for $emailService
106 6
     *
107 2
     * @param EmailService $emailService
108 2
     */
109 2
    public function injectEmailService(\DERHANSEN\SfEventMgt\Service\EmailService $emailService)
110 2
    {
111 2
        $this->emailService = $emailService;
112
    }
113 2
114 2
    /**
115 2
     * DI for $fluidStandaloneService
116 2
     *
117 2
     * @param FluidStandaloneService $fluidStandaloneService
118 6
     */
119 6
    public function injectFluidStandaloneService(
120
        \DERHANSEN\SfEventMgt\Service\FluidStandaloneService $fluidStandaloneService
121
    ) {
122
        $this->fluidStandaloneService = $fluidStandaloneService;
123
    }
124
125
    /**
126
     * DI for $hashService
127
     *
128
     * @param \TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService
129
     */
130
    public function injectHashService(\TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService)
131 8
    {
132
        $this->hashService = $hashService;
133 8
    }
134
135
    /**
136
     * DI for $objectManager
137
     *
138
     * @param \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager
139
     */
140
    public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManager $objectManager)
141
    {
142
        $this->objectManager = $objectManager;
143
    }
144
145 2
    /**
146
     * DI for $registrationRepository
147 2
     *
148 2
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
149 2
     */
150 2
    public function injectRegistrationRepository(
151 2
        \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
152 2
    ) {
153 2
        $this->registrationRepository = $registrationRepository;
154
    }
155
156
    /**
157
     * @param EventDispatcherInterface $eventDispatcher
158
     */
159
    public function injectEventDispatcher(EventDispatcherInterface $eventDispatcher)
160
    {
161
        $this->eventDispatcher = $eventDispatcher;
162
    }
163
164
    /**
165
     * Sends a custom notification defined by the given customNotification key
166 34
     * to all confirmed users of the event
167
     *
168 34
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
169
     * @param string $customNotification CustomNotification
170 34
     * @param array $settings Settings
171 4
     *
172
     * @return int Number of notifications sent
173
     */
174 30
    public function sendCustomNotification($event, $customNotification, $settings)
175 20
    {
176 20
        if ($this->cantSendCustomNotification($event, $settings, $customNotification)) {
177 20
            return 0;
178 20
        }
179 20
        $count = 0;
180
181 20
        $constraints = $settings['notification']['customNotifications'][$customNotification]['constraints'];
182 20
        $registrations = $this->registrationRepository->findNotificationRegistrations($event, $constraints);
183 20
        foreach ($registrations as $registration) {
184 20
            /** @var \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration */
185 20
            if ($registration->isConfirmed() && !$registration->isIgnoreNotifications()) {
186 20
                $result = $this->sendUserMessage(
187 20
                    $event,
188
                    $registration,
189 20
                    $settings,
190
                    MessageType::CUSTOM_NOTIFICATION,
191 10
                    $customNotification
192
                );
193
                if ($result) {
194
                    $count += 1;
195
                }
196
            }
197
        }
198
199
        return $count;
200
    }
201
202 34
    /**
203
     * Returns true if conditions are not met to send a custom notification
204 34
     *
205 34
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event
206
     * @param array $settings
207 34
     * @param string $customNotification
208 6
     *
209 6
     * @return bool
210 6
     */
211 28
    protected function cantSendCustomNotification($event, $settings, $customNotification)
212 6
    {
213 6
        return is_null($event) || $customNotification == '' || $settings == '' || !is_array($settings);
214 6
    }
215 22
216 6
    /**
217 6
     * Adds a logentry to the custom notification log
218 6
     *
219 16
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
220
     * @param string $details Details
221
     * @param int $emailsSent E-Mails sent
222
     */
223 16
    public function createCustomNotificationLogentry($event, $details, $emailsSent)
224 2
    {
225 2
        $notificationlogEntry = new \DERHANSEN\SfEventMgt\Domain\Model\CustomNotificationLog();
226 2
        $notificationlogEntry->setEvent($event);
227 14
        $notificationlogEntry->setDetails($details);
228 14
        $notificationlogEntry->setEmailsSent($emailsSent);
229 14
        $notificationlogEntry->setCruserId($GLOBALS['BE_USER']->user['uid']);
230
        $this->customNotificationLogRepository->add($notificationlogEntry);
231 34
    }
232
233 34
    /**
234
     * Sends a message to the user based on the given type
235
     *
236
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
237
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
238
     * @param array $settings Settings
239
     * @param int $type Type
240
     * @param string $customNotification CustomNotification
241
     *
242
     * @return bool TRUE if successful, else FALSE
243
     */
244
    public function sendUserMessage($event, $registration, $settings, $type, $customNotification = '')
245
    {
246 52
        list($template, $subject) = $this->getUserMessageTemplateSubject($settings, $type, $customNotification);
247
248 52
        if (is_null($event) || is_null($registration) || is_null($type) || !is_array($settings) ||
249
            (substr($template, -5) != '.html') || (bool)$settings['notification']['disabled']
250
        ) {
251 52
            return false;
252 50
        }
253 52
254 12
        if (!$registration->isIgnoreNotifications()) {
255
            $body = $this->getNotificationBody($event, $registration, $template, $settings);
256
            $subject = $this->fluidStandaloneService->parseStringFluid(
257 40
                $subject,
258 40
                [
259 40
                    'event' => $event,
260 40
                    'registration' => $registration
261 40
                ]
262 40
            );
263
            $attachments = $this->attachmentService->getAttachments(
264 40
                $settings,
265 40
                $registration,
266 30
                $type,
267 30
                MessageRecipient::USER
268 30
            );
269 30
270 30
            // Get iCal attachment if configured
271 30
            $iCalAttachment = $this->attachmentService->getICalAttachment(
272 30
                $settings,
273 30
                $registration,
274
                $type,
275 30
                MessageRecipient::USER
276 30
            );
277 30
278 40
            if ($iCalAttachment !== '') {
279 10
                $attachments[] = $iCalAttachment;
280 10
            }
281 10
282 10
            $modifyUserMessageSenderEvent = new ModifyUserMessageSenderEvent(
283 10
                $settings['notification']['senderName'] ?? '',
284 10
                $settings['notification']['senderEmail'] ?? '',
285
                $settings['notification']['replyToEmail'] ?? '',
286 10
                $registration,
287 10
                $type,
288 40
                $this
289
            );
290
            $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...
291
            $senderName = $modifyUserMessageSenderEvent->getSenderName();
292
            $senderEmail = $modifyUserMessageSenderEvent->getSenderEmail();
293
            $replyToEmail = $modifyUserMessageSenderEvent->getReplyToEmail();
294
295
            $modifyUserAttachmentsEvent = new ModifyUserMessageAttachmentsEvent(
296
                $attachments,
297
                $registration,
298 52
                $type,
299
                $this
300 52
            );
301 52
            $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...
302
            $attachments = $modifyUserAttachmentsEvent->getAttachments();
303 52
304 10
            $result = $this->emailService->sendEmailMessage(
305 10
                $senderEmail,
306 10
                $registration->getEmail(),
307 42
                $subject,
308 10
                $body,
309 10
                $senderName,
310 10
                $attachments,
311 32
                $replyToEmail
312 10
            );
313 10
314 10
            $afterUserMessageSentEvent = new AfterUserMessageSentEvent(
315 22
                $registration,
316
                $body,
317
                $subject,
318
                $attachments,
319 22
                $senderName,
320 22
                $senderEmail,
321 22
                $replyToEmail,
322
                $this
323 52
            );
324
            $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...
325 52
326
            // Cleanup iCal attachment if available
327
            if ($iCalAttachment !== '') {
328
                \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile($iCalAttachment);
329
            }
330
331
            return $result;
332
        }
333
334
        return false;
335
    }
336
337
    /**
338 60
     * Returns an array with template and subject for the user message
339
     *
340
     * @param array $settings
341 60
     * @param int $type Type
342 60
     * @param string $customNotification
343 60
     * @return array
344 60
     */
345
    protected function getUserMessageTemplateSubject($settings, $type, $customNotification)
346 60
    {
347
        $template = 'Notification/User/RegistrationNew.html';
348
        $subject = $settings['notification']['registrationNew']['userSubject'];
349
        switch ($type) {
350
            case MessageType::REGISTRATION_WAITLIST_NEW:
351
                $template = 'Notification/User/RegistrationWaitlistNew.html';
352 60
                $subject = $settings['notification']['registrationWaitlistNew']['userSubject'];
353 60
                break;
354 60
            case MessageType::REGISTRATION_CONFIRMED:
355 60
                $template = 'Notification/User/RegistrationConfirmed.html';
356 60
                $subject = $settings['notification']['registrationConfirmed']['userSubject'];
357 60
                break;
358 60
            case MessageType::REGISTRATION_WAITLIST_CONFIRMED:
359 60
                $template = 'Notification/User/RegistrationWaitlistConfirmed.html';
360 60
                $subject = $settings['notification']['registrationWaitlistConfirmed']['userSubject'];
361 60
                break;
362 60
            case MessageType::REGISTRATION_CANCELLED:
363 60
                $template = 'Notification/User/RegistrationCancelled.html';
364
                $subject = $settings['notification']['registrationCancelled']['userSubject'];
365
                break;
366
            case MessageType::CUSTOM_NOTIFICATION:
367
                $template = 'Notification/User/Custom/' . $settings['notification']['customNotifications'][$customNotification]['template'];
368
                $subject = $settings['notification']['customNotifications'][$customNotification]['subject'];
369
                break;
370
            case MessageType::REGISTRATION_NEW:
371
            default:
372
        }
373
374
        return [
375
            $template,
376
            $subject
377
        ];
378
    }
379
380
    /**
381
     * Sends a message to the admin based on the given type
382
     *
383
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Event $event Event
384
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration Registration
385
     * @param array $settings Settings
386
     * @param int $type Type
387
     *
388
     * @return bool TRUE if successful, else FALSE
389
     */
390
    public function sendAdminMessage($event, $registration, $settings, $type)
391
    {
392
        list($template, $subject) = $this->getAdminMessageTemplateSubject($settings, $type);
393
394
        if (is_null($event) || is_null($registration || !is_array($settings)) ||
395
            ($event->getNotifyAdmin() === false && $event->getNotifyOrganisator() === false) ||
396
            (bool)$settings['notification']['disabled']
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