Completed
Push — master ( 80f1a6...8c34ac )
by Dominik
03:50
created

getDateTimeOfLastNewsletter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
namespace Azine\EmailBundle\Services;
3
use Azine\EmailBundle\Entity\Repositories\NotificationRepository;
4
use Doctrine\Common\Persistence\ManagerRegistry;
5
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
6
use Azine\EmailBundle\DependencyInjection\AzineEmailExtension;
7
use Azine\EmailBundle\Entity\Notification;
8
use Azine\EmailBundle\Entity\RecipientInterface;
9
use Doctrine\ORM\EntityManager;
10
use Monolog\Logger;
11
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
12
13
/**
14
 * This Service compiles and renders the emails to be sent.
15
 * @author Dominik Businger
16
 */
17
class AzineNotifierService implements NotifierServiceInterface
18
{
19
    /**
20
     * Override this function to fill in any non-recipient-specific parameters that are required to
21
     * render the notifications-template or one of the  notification-item-templates that
22
     * are rendered into the notifications-template
23
     *
24
     * @return array
25
     */
26 3
    protected function getVarsForNotificationsEmail()
27
    {
28 3
        $params = array();
29
30 3
        return $params;
31
    }
32
33
    /**
34
     * Override this function to fill in any recipient-specific parameters that are required to
35
     * render the notifications-template or one of the  notification-item-templates that
36
     * are rendered into the notifications-template
37
     *
38
     * @param  RecipientInterface $recipient
39
     * @return array
40
     */
41 2
    protected function getRecipientVarsForNotificationsEmail(RecipientInterface $recipient)
42
    {
43 2
        $recipientParams = array();
44 2
        $recipientParams['recipient'] = $recipient;
45 2
        $recipientParams['mode'] = $recipient->getNotificationMode();
46
47 2
        return $recipientParams;
48
    }
49
50
    /**
51
     * Get the subject for the notifications-email to send. Override this function to implement your custom subject-lines.
52
     * @param  array of array     $contentItems
53
     * @param  RecipientInterface $recipient
54
     * @return string
55
     */
56 2
    public function getRecipientSpecificNotificationsSubject($contentItems, RecipientInterface $recipient)
57
    {
58 2
        $count = sizeof($contentItems);
59
60 2
        if($count == 1){
61
        	// get the content-item out of the boxed associative array => array(array('templateId' => contentItem))
62 2
        	$onlyItem = current(current($contentItems));
63
        	// get the title out of the notification in the contentItem
64 2
        	return $onlyItem['notification']->getTitle();
65
        }
66
67
        return $this->translatorService->transChoice("_az.email.notifications.subject.%count%", $count, array('%count%' => $count));
68
    }
69
70
    /**
71
     * Override this function to fill in any non-recipient-specific parameters that are required
72
     * to render the newsletter-template and are not provided by the TemplateProvider. e.g. the total number of recipients of this newsletter
73
     *
74
     * @return array
75
     */
76 1
    protected function getGeneralVarsForNewsletter()
77
    {
78 1
        $vars = array();
79 1
        $vars['recipientCount'] = sizeof($this->recipientProvider->getNewsletterRecipientIDs());
80
81 1
        return $vars;
82
    }
83
84
    /**
85
     * Override this function to fill in any non-recipient-specific content items that are the same
86
     * for all recipients of the newsletter.
87
     *
88
     * E.g. a list of featured events or news-articles.
89
     *
90
     * @return array of templatesIds (without ending) as key and params to render the template as value. => array('AzineEmailBundle:contentItem:message' => array('notification => $someNotification, 'goToUrl' => 'http://example.com', ...));
91
     */
92
    protected function getNonRecipientSpecificNewsletterContentItems()
93
    {
94
        // @codeCoverageIgnoreStart
95
        $contentItems = array();
96
97
        //$contentItems[] = array('AcmeBundle:foo:barSameForAllRecipientsTemplate' => $templateParams);
98
        return $contentItems;
99
        // @codeCoverageIgnoreEnd
100
    }
101
102
    /**
103
     * Override this function to add more parameters that are required to render the newsletter template.
104
     * @param  RecipientInterface           $recipient
105
     * @return array
106
     */
107 2
    public function getRecipientSpecificNewsletterParams(RecipientInterface $recipient)
108
    {
109 2
        return array('recipient' => $recipient);
110
    }
111
112
    /**
113
     * Override this function to fill in any recipient-specific content items that are different
114
     * depending on the recipient of the newsletter.
115
     *
116
     * E.g. a list of the recipients latest activites.
117
     *
118
     * @param  RecipientInterface $recipient
119
     * @return array              of arrays with templatesIds (without ending) as key and params to render the template as value.
120
     *                                      => array(
121
     *                                      array('AzineEmailBundle:contentItem:message' => array('notification => $someNotification1, 'goToUrl' => 'http://example.com/1', ...))
122
     *                                      array('AzineEmailBundle:contentItem:message' => array('notification => $someNotification2, 'goToUrl' => 'http://example.com/2', ...))
123
     *                                      );
124
     */
125
    protected function getRecipientSpecificNewsletterContentItems(RecipientInterface $recipient)
0 ignored issues
show
Unused Code introduced by
The parameter $recipient is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
126
    {
127
        // @codeCoverageIgnoreStart
128
        $contentItems = array();
129
130
        //$contentItems[] = array('AcmeBundle:foo:barDifferentForEachRecipientTemplate' => $recipientSpecificTemplateParams);
131
        //$contentItems[] = array(AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TEMPLATE => array('notification' => array('title' => 'SampleMessage', 'created' => new \DateTime('1 hour ago'), 'content' => 'Sample Text. Lorem Ipsum.')));
132
        return $contentItems;
133
        // @codeCoverageIgnoreEnd
134
    }
135
136
    /**
137
     * Override this function to use a custom subject line for each newsletter-recipient.
138
     *
139
     * @param $generalContentItems array of content items. => e.g. array of array('templateID' => array('notification => $someNotification, 'goToUrl' => 'http://example.com', ...))
140
     * @param $recipientContentItems array of content items. => e.g. array of array('templateID' => array('notification => $someNotification, 'goToUrl' => 'http://example.com', ...))
141
     * @param $params array the array with all general template-params, including the item with the key 'subject' containing the default-subject
142
     * @param $recipient RecipientInterface
143
     * @param $locale string The language-code for translation of the subject
144
     * @return the subject line
145
     */
146 1
    public function getRecipientSpecificNewsletterSubject(array $generalContentItems, array $recipientContentItems, array $params, RecipientInterface $recipient, $locale)
147
    {
148 1
        return $params['subject'];
149
    }
150
151
    /**
152
     * By overriding this function you can rearrange the content items to you liking. By default no ordering is done, so the order is as follows:
153
     *
154
     * - all user-specific content items as returned by AzineNotifierService::getRecipientSpecificNewsletterContentItems
155
     * - all non-user-specific content items as returned by AzineNotifierService::getNonRecipientSpecificNewsletterContentItems
156
     *
157
     * @param array $contentItems
158
     * @return array
159
     */
160 2
    public function orderContentItems(array $contentItems){
161 2
        return $contentItems;
162
    }
163
164
    /**
165
     * Over ride this constructor if you need to inject more dependencies to get all the data together that you need for your newsletter/notifications.
166
     *
167
     * @param TemplateTwigSwiftMailerInterface $mailer
168
     * @param \Twig_Environment                $twig
169
     * @param Logger                           $logger
170
     * @param UrlGeneratorInterface            $router
171
     * @param ManagerRegistry                  $managerRegistry
172
     * @param TemplateProviderInterface        $templateProvider
173
     * @param RecipientProviderInterface       $recipientProvider
174
     * @param Translator                       $translatorService
175
     * @param array                            $parameters
176
     */
177 8
    public function __construct(TemplateTwigSwiftMailerInterface $mailer, \Twig_Environment $twig, Logger $logger, UrlGeneratorInterface $router,
178
                               ManagerRegistry $managerRegistry, TemplateProviderInterface $templateProvider, RecipientProviderInterface $recipientProvider,
179
            Translator $translatorService, array $parameters) {
180
181 8
        $this->mailer = $mailer;
182 8
        $this->twig = $twig;
183 8
        $this->logger = $logger;
184 8
        $this->router = $router;
185 8
        $this->managerRegistry = $managerRegistry;
186 8
        $this->templateProvider = $templateProvider;
187 8
        $this->recipientProvider = $recipientProvider;
188 8
        $this->translatorService = $translatorService;
189 8
        $this->configParameter = $parameters;
190 8
    }
191
192
    //////////////////////////////////////////////////////////////////////////
193
    /* You probably don't need to change or override any of the stuff below */
194
    //////////////////////////////////////////////////////////////////////////
195
196
    const CONTENT_ITEMS = 'contentItems';
197
    /**
198
     * @var TemplateTwigSwiftMailerInterface
199
     */
200
    protected $mailer;
201
202
    /**
203
     * @var \Twig_Environment
204
     */
205
    protected $twig;
206
207
    /**
208
     * @var Logger
209
     */
210
    protected $logger;
211
212
    /**
213
     * @var UrlGeneratorInterface
214
     */
215
    protected $router;
216
217
    /**
218
     * @var TemplateProviderInterface
219
     */
220
    protected $templateProvider;
221
222
    /**
223
     * @var RecipientProviderInterface
224
     */
225
    protected $recipientProvider;
226
227
    /**
228
     * @var ManagerRegistry
229
     */
230
    protected $managerRegistry;
231
232
    /**
233
     * Array of configuration-parameters from the config.yml
234
     * @var array
235
     */
236
    protected $configParameter;
237
238
    /**
239
     * The translator
240
     * @var Translator
241
     */
242
    protected $translatorService;
243
244
    /**
245
     * Get the number of seconds in a "one-hour-interval"
246
     * @return integer of seconds to consider as an hour.
247
     */
248 4
    protected function getHourInterval()
249
    {
250
        // about an hour ago (57min)
251
        // this is because if the last run started 60min. ago, then the notifications
252
        // for any recipient have been send after that and would be skipped until the next run.
253
        // if your cron-job runs every minute, this is not needed.
254 4
        return 	60*60 - 3*60;
255
    }
256
257
    /**
258
     * Get the number of seconds in a "one-day-interval"
259
     * @return integer of seconds to consider as a day.
260
     */
261 3
    protected function getDayInterval()
262
    {
263
        // about a day ago (23h57min)
264
        // this is because if the last run started 24h. ago, then the notifications
265
        // for any recipient have been send after that and would be skipped until the next run.
266
        // if your cron-job runs every minute, this is not needed.
267 3
        return 60 * 60 * 24 - 3 * 60;
268
    }
269
270
    /**
271
     * (non-PHPdoc)
272
     * @see Azine\EmailBundle\Services.NotifierServiceInterface::sendNotifications()
273
     */
274 3
    public function sendNotifications(array &$failedAddresses)
275
    {
276
        // get all recipientIds with pending notifications in the database, that are due to be sent
277 3
        $recipientIds = $this->getNotificationRecipientIds();
278
279
        // get vars that are the same for all recipients of this notification-mail-batch
280 3
        $params = $this->getVarsForNotificationsEmail();
281
282 3
        $notificationsTemplate = $this->configParameter[AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::NOTIFICATIONS_TEMPLATE];
283
284 3
        foreach ($recipientIds as $recipientId) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
285
286
            // send the mail for this recipient
287 3
            $failedAddress = $this->sendNotificationsFor($recipientId, $notificationsTemplate, $params);
288
289 3
            if ($failedAddress !== null && strlen($failedAddress) > 0) {
290 2
                $failedAddresses[] = $failedAddress;
291 2
            }
292 3
        }
293
294
        // log mail-errors as warnings
295 3
        if (sizeof($failedAddresses) > 0) {
296 2
            $this->logger->warn("Failed to send message to :\n".print_r($failedAddresses, true));
297 2
        }
298
299 3
        return sizeof($recipientIds) - sizeof($failedAddresses);
300
    }
301
302
    /**
303
     * Send the notifications-email for one recipient
304
     * @param  integer     $recipientId
305
     * @param  string      $wrapperTemplateName
306
     * @param  array       $params              array of parameters for this recipient
307
     * @return null|string or the failed email addressess
308
     */
309 3
    public function sendNotificationsFor($recipientId, $wrapperTemplateName, $params)
310
    {
311
        // get the recipient
312 3
        $recipient = $this->recipientProvider->getRecipient($recipientId);
313
314
        // get all Notification-Items for the recipient from the database
315 3
        $notifications = $this->getNotificationsFor($recipient);
316 3
        if (sizeof($notifications) == 0 ) {
317 1
            return null;
318
        }
319
320
        // get the recipient specific parameters for the twig-templates
321 2
        $recipientParams = $this->getRecipientVarsForNotificationsEmail($recipient);
322 2
        $params = array_merge($recipientParams, $params);
323
324
        // prepare the arrays with template and template-variables for each notification
325 2
        $contentItems = array();
326 2
        foreach ($notifications as $notification) {
327
328
            // decode the $params from the json in the notification-entity
329 2
            $itemVars = $notification->getVariables();
330 2
            $itemVars = array_merge($params, $itemVars);
331 2
            $itemVars['notification'] = $notification;
332 2
            $itemVars['recipient'] = $recipient;
333
334 2
            $itemTemplateName = $notification->getTemplate();
335
336 2
            $contentItems[] = array($itemTemplateName => $itemVars);
337 2
        }
338
339
        // add the notifications to the params array so they will be rendered later
340 2
        $params[self::CONTENT_ITEMS] = $contentItems;
341 2
        $params['recipient'] = $recipient;
342 2
        $params['_locale'] = $recipient->getPreferredLocale();
343
344 2
        $subject = $this->getRecipientSpecificNotificationsSubject($contentItems, $recipient);
345
346
        // send the email with the right wrapper-template
347 2
        $sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $params, $wrapperTemplateName . ".txt.twig", $recipient->getPreferredLocale());
348
349 2
        if ($sent) {
350
            // save the updated notifications
351 2
            $this->setNotificationsAsSent($notifications);
352
353 2
            return null;
354
355
        } else {
356 2
            $this->logger->error("The notification for ".$recipient->getDisplayName()." <".$recipient->getEmail()."> could not be sent!", $params);
357
358 2
            return $recipient->getEmail();
359
360
        }
361
    }
362
363
    /**
364
     * (non-PHPdoc)
365
     * @see Azine\EmailBundle\Services.NotifierServiceInterface::sendNewsletter()
366
     */
367 2
    public function sendNewsletter(array &$failedAddresses)
368
    {
369
        // params array for all recipients
370 2
        $params = array();
371
372
        // set a default subject
373 2
        $params['subject'] = $this->translatorService->trans("_az.email.newsletter.subject");
374
375
        // get the the non-recipient-specific contentItems of the newsletter
376 2
        $params[self::CONTENT_ITEMS] = $this->getNonRecipientSpecificNewsletterContentItems();
377
378
        // get recipientIds for the newsletter
379 2
        $recipientIds = $this->recipientProvider->getNewsletterRecipientIDs();
380
381 2
        $newsletterTemplate = $this->configParameter[AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::NEWSLETTER_TEMPLATE];
382
383 2
        foreach ($recipientIds as $recipientId) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
384 2
            $failedAddress = $this->sendNewsletterFor($recipientId, $params, $newsletterTemplate);
385
386 2
            if ($failedAddress !== null && strlen($failedAddress) > 0) {
387 2
                $failedAddresses[] = $failedAddress;
388 2
            }
389 2
        }
390
391 2
        return sizeof($recipientIds) - sizeof($failedAddresses);
392
    }
393
394
    /**
395
     * Send the newsletter for one recipient
396
     * @param  integer     $recipientId
397
     * @param  array       $params          params and contentItems that are the same for all recipients
398
     * @param  string      $wrapperTemplate
399
     * @return string|null or the failed email addressess
400
     */
401 2
    public function sendNewsletterFor($recipientId, array $params, $wrapperTemplate)
402
    {
403 2
        $recipient = $this->recipientProvider->getRecipient($recipientId);
404
405
        // create new array for each recipient.
406 2
        $recipientParams = array_merge($params, $this->getRecipientSpecificNewsletterParams($recipient));
407
408
        // get the recipient-specific contentItems of the newsletter
409 2
        $recipientContentItems = $this->getRecipientSpecificNewsletterContentItems($recipient);
410
411
        // merge the recipient-specific and the general content items. recipient-specific first/at the top!
412 2
        $recipientParams[self::CONTENT_ITEMS] = $this->orderContentItems(array_merge($recipientContentItems,  $params[self::CONTENT_ITEMS]));
413 2
        $recipientParams['_locale'] = $recipient->getPreferredLocale();
414
415 2 View Code Duplication
        if (sizeof($recipientParams[self::CONTENT_ITEMS]) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
416 1
            $this->logger->warning("The newsletter for '".$recipient->getDisplayName()." <".$recipient->getEmail().">' has not been sent. It would have been empty.", $params);
417
418 1
            return $recipient->getEmail();
419
        }
420
421 1
        $subject = $this->getRecipientSpecificNewsletterSubject($params[self::CONTENT_ITEMS], $recipientContentItems, $params, $recipient, $recipient->getPreferredLocale());
422
423
        // render and send the email with the right wrapper-template
424 1
        $sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $recipientParams, $wrapperTemplate.".txt.twig", $recipient->getPreferredLocale());
425
426 1 View Code Duplication
        if ($sent) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
427
            // save that this recipient has recieved the newsletter
428 1
            return null;
429
430
        } else {
431 1
            $this->logger->error("The newsletter for ".$recipient->getDisplayName()." <".$recipient->getEmail()."> could not be sent!", $params);
432
433 1
            return $recipient->getEmail();
434
435
        }
436
    }
437
438
    /**
439
     * Get the Notifications that have not yet been sent yet.
440
     * Ordered by "template" and "title".
441
     * @param  RecipientInterface $recipient
442
     * @return array              of Notification
443
     */
444 3
    protected function getNotificationsFor(RecipientInterface $recipient)
445
    {
446
        // get the notification mode
447 3
        $notificationMode = $recipient->getNotificationMode();
448
449
        // get the date/time of the last notification
450 3
        $lastNotificationDate = $this->getNotificationRepository()->getLastNotificationDate($recipient->getId());
451
452 3
        $sendNotifications = false;
453 3
        $timeDelta = time() - $lastNotificationDate->getTimestamp();
454
455 3
        if ($notificationMode == RecipientInterface::NOTIFICATION_MODE_IMMEDIATELY) {
456 3
            $sendNotifications = true;
457
458 3
        } elseif ($notificationMode == RecipientInterface::NOTIFICATION_MODE_HOURLY) {
459 3
            $sendNotifications = ($timeDelta > $this->getHourInterval());
460
461 3
        } elseif ($notificationMode == RecipientInterface::NOTIFICATION_MODE_DAYLY) {
462 3
            $sendNotifications = ($timeDelta > $this->getDayInterval());
463
464 3
        } elseif ($notificationMode == RecipientInterface::NOTIFICATION_MODE_NEVER) {
465
            $this->markAllNotificationsAsSentFarInThePast($recipient);
466
467
            return array();
468
        }
469
470
        // regularly sent notifications now
471 3
        if ($sendNotifications) {
472 3
            $notifications = $this->getNotificationRepository()->getNotificationsToSend($recipient->getId());
473
474
        // if notifications exist, that should be sent immediately, then send those now disregarding the users mailing-preferences.
475 3
        } else {
476
            $notifications = $this->getNotificationRepository()->getNotificationsToSendImmediately($recipient->getId());
477
        }
478
479 3
        return $notifications;
480
    }
481
482
    /**
483
     * Get all IDs for Recipients of pending notifications
484
     * @return array of IDs
485
     */
486 3
    protected function getNotificationRecipientIds()
487
    {
488 3
        return $this->getNotificationRepository()->getNotificationRecipientIds();
489
    }
490
491
    /**
492
     * Update (set sent = now) and save the notifications
493
     * @param array $notifications
494
     */
495 2
    protected function setNotificationsAsSent(array $notifications)
496
    {
497 2
        foreach ($notifications as $notification) {
498 2
            $notification->setSent(new \DateTime());
499 2
            $this->managerRegistry->getManager()->persist($notification);
500 2
        }
501 2
        $this->managerRegistry->getManager()->flush();
502 2
    }
503
504
    /**
505
     * Mark all Notifications as sent long ago, as the recipient never want's to get any notifications.
506
     * @param RecipientInterface $recipient
507
     */
508 1
    protected function markAllNotificationsAsSentFarInThePast(RecipientInterface $recipient)
509
    {
510 1
        $this->getNotificationRepository()->markAllNotificationsAsSentFarInThePast($recipient->getId());
511 1
    }
512
513
    /**
514
     * Get the interval in days between newsletter mailings
515
     */
516 1
    protected function getNewsletterInterval()
517
    {
518 1
        return $this->configParameter[AzineEmailExtension::NEWSLETTER."_".AzineEmailExtension::NEWSLETTER_INTERVAL];
519
    }
520
521
    /**
522
     * Get the time of the day when the newsletter should be sent.
523
     * @return string Time of the day in the format HH:mm
524
     */
525 1
    protected function getNewsletterSendTime()
526
    {
527 1
        return $this->configParameter[AzineEmailExtension::NEWSLETTER."_".AzineEmailExtension::NEWSLETTER_SEND_TIME];
528
    }
529
530
    /**
531
     * Get the DateTime at which the last newsletter mailing probably has taken place, if a newsletter is sent today.
532
     * (Calculated: send-time-today - interval in days)
533
     * @return \DateTime
534
     */
535 1
    protected function getDateTimeOfLastNewsletter()
536
    {
537 1
        return new \DateTime($this->getNewsletterInterval()." days ago ".$this->getNewsletterSendTime());
538
    }
539
540
    /**
541
     * Get the DateTime at which the next newsletter mailing will take place, if a newsletter is sent today.
542
     * (Calculated: send-time-today + interval in days)
543
     */
544 1
    protected function getDateTimeOfNextNewsletter()
545
    {
546 1
        return new \DateTime("+".$this->getNewsletterInterval()." days  ".$this->getNewsletterSendTime());
547
    }
548
549
    /**
550
     * Convenience-function to add and save a Notification-entity
551
     *
552
     * @param  integer      $recipientId     the ID of the recipient of this notification => see RecipientProvider.getRecipient($id)
553
     * @param  string       $title           the title of the notification. depending on the recipients settings, multiple notifications are sent in one email.
554
     * @param  string       $content         the content of the notification
555
     * @param  string       $template        the twig-template to render the notification with
556
     * @param  array        $templateVars    the parameters used in the twig-template, 'notification' => Notification and 'recipient' => RecipientInterface will be added to this array when rendering the twig-template.
557
     * @param  integer      $importance      important messages are at the top of the notification-emails, un-important at the bottom.
558
     * @param  boolean      $sendImmediately whether or not to ignore the recipients mailing-preference and send the notification a.s.a.p.
559
     * @return Notification
560
     */
561 2
    public function addNotification($recipientId, $title, $content, $template, $templateVars, $importance, $sendImmediately)
562
    {
563 2
        $notification = new Notification();
564 2
        $notification->setRecipientId($recipientId);
565 2
        $notification->setTitle($title);
566 2
        $notification->setContent($content);
567 2
        $notification->setTemplate($template);
568 2
        $notification->setImportance($importance);
569 2
        $notification->setSendImmediately($sendImmediately);
570 2
        $notification->setVariables($templateVars);
571 2
        $this->managerRegistry->getManager()->persist($notification);
572 2
        $this->managerRegistry->getManager()->flush($notification);
573
574 2
        return $notification;
575
    }
576
577
    /**
578
     * Convenience-function to add and save a Notification-entity for a message => see AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TYPE
579
     *
580
     * The following default are used:
581
     * $importance		= NORMAL
582
     * $sendImmediately	= fale
583
     * $template		= template for type AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TYPE
584
     * $templateVars	= only those from the template-provider
585
     *
586
     * @param integer $recipientId
587
     * @param string  $title
588
     * @param string  $content     nl2br will be applied in the html-version of the email
589
     * @param string  $goToUrl     if this is supplied, a link "Go to message" will be added.
590
     */
591 1
    public function addNotificationMessage($recipientId, $title, $content, $goToUrl = null)
592
    {
593 1
        $contentItemTemplate = $this->configParameter[AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::CONTENT_ITEM_TEMPLATE];
594 1
        $templateVars = array();
595 1
        if ($goToUrl !== null && strlen($goToUrl) > 0) {
596 1
            $templateVars['goToUrl'] = $goToUrl;
597 1
        }
598 1
        $this->addNotification($recipientId, $title, $content, $contentItemTemplate, $this->templateProvider->addTemplateVariablesFor($contentItemTemplate, $templateVars), Notification::IMPORTANCE_NORMAL, false);
599 1
    }
600
601
602
    /**
603
     * @return NotificationRepository
604
     */
605 4
    protected function getNotificationRepository(){
606 4
        return $this->managerRegistry->getRepository('AzineEmailBundle::Notification');
607
    }
608
609
}
610