Completed
Push — master ( 62fece...6b6b0d )
by Dominik
03:49
created

getDateTimeOfNextNewsletter()   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 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
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
        $sentCount = 0;
285 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...
286
287
            // send the mail for this recipient
288 3
            $failedAddress = $this->sendNotificationsFor($recipientId, $notificationsTemplate, $params);
289 3
            if ($failedAddress !== null && strlen($failedAddress) > 0) {
290 2
                $failedAddresses[] = $failedAddress;
291 2
            } else {
292 3
                $sentCount++;
293
            }
294 3
        }
295
296
        // log mail-errors as warnings
297 3
        if (sizeof($failedAddresses) > 0) {
298 2
            $this->logger->warn("Failed to send message to :\n".print_r($failedAddresses, true));
299 2
        }
300
301 3
        return $sentCount;
302
    }
303
304
    /**
305
     * Send the notifications-email for one recipient
306
     * @param  integer     $recipientId
307
     * @param  string      $wrapperTemplateName
308
     * @param  array       $params              array of parameters for this recipient
309
     * @return null|string or the failed email addressess
310
     */
311 3
    public function sendNotificationsFor($recipientId, $wrapperTemplateName, $params)
312
    {
313
        // get the recipient
314 3
        $recipient = $this->recipientProvider->getRecipient($recipientId);
315
316
        // get all Notification-Items for the recipient from the database
317 3
        $notifications = $this->getNotificationsFor($recipient);
318 3
        if (sizeof($notifications) == 0 ) {
319 1
            return null;
320
        }
321
322
        // get the recipient specific parameters for the twig-templates
323 2
        $recipientParams = $this->getRecipientVarsForNotificationsEmail($recipient);
324 2
        $params = array_merge($recipientParams, $params);
325
326
        // prepare the arrays with template and template-variables for each notification
327 2
        $contentItems = array();
328 2
        foreach ($notifications as $notification) {
329
330
            // decode the $params from the json in the notification-entity
331 2
            $itemVars = $notification->getVariables();
332 2
            $itemVars = array_merge($params, $itemVars);
333 2
            $itemVars['notification'] = $notification;
334 2
            $itemVars['recipient'] = $recipient;
335
336 2
            $itemTemplateName = $notification->getTemplate();
337
338 2
            $contentItems[] = array($itemTemplateName => $itemVars);
339 2
        }
340
341
        // add the notifications to the params array so they will be rendered later
342 2
        $params[self::CONTENT_ITEMS] = $contentItems;
343 2
        $params['recipient'] = $recipient;
344 2
        $params['_locale'] = $recipient->getPreferredLocale();
345
346 2
        $subject = $this->getRecipientSpecificNotificationsSubject($contentItems, $recipient);
347
348
        // send the email with the right wrapper-template
349 2
        $sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $params, $wrapperTemplateName . ".txt.twig", $recipient->getPreferredLocale());
350
351 2
        if ($sent) {
352
            // save the updated notifications
353 2
            $this->setNotificationsAsSent($notifications);
354
355 2
            return null;
356
357
        } else {
358 2
            $this->logger->error("The notification for ".$recipient->getDisplayName()." <".$recipient->getEmail()."> could not be sent!", $params);
359
360 2
            return $recipient->getEmail();
361
362
        }
363
    }
364
365
    /**
366
     * (non-PHPdoc)
367
     * @see Azine\EmailBundle\Services.NotifierServiceInterface::sendNewsletter()
368
     */
369 2
    public function sendNewsletter(array &$failedAddresses)
370
    {
371
        // params array for all recipients
372 2
        $params = array();
373
374
        // set a default subject
375 2
        $params['subject'] = $this->translatorService->trans("_az.email.newsletter.subject");
376
377
        // get the the non-recipient-specific contentItems of the newsletter
378 2
        $params[self::CONTENT_ITEMS] = $this->getNonRecipientSpecificNewsletterContentItems();
379
380
        // get recipientIds for the newsletter
381 2
        $recipientIds = $this->recipientProvider->getNewsletterRecipientIDs();
382
383 2
        $newsletterTemplate = $this->configParameter[AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::NEWSLETTER_TEMPLATE];
384
385 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...
386 2
            $failedAddress = $this->sendNewsletterFor($recipientId, $params, $newsletterTemplate);
387
388 2
            if ($failedAddress !== null && strlen($failedAddress) > 0) {
389 2
                $failedAddresses[] = $failedAddress;
390 2
            }
391 2
        }
392
393 2
        return sizeof($recipientIds) - sizeof($failedAddresses);
394
    }
395
396
    /**
397
     * Send the newsletter for one recipient
398
     * @param  integer     $recipientId
399
     * @param  array       $params          params and contentItems that are the same for all recipients
400
     * @param  string      $wrapperTemplate
401
     * @return string|null or the failed email addressess
402
     */
403 2
    public function sendNewsletterFor($recipientId, array $params, $wrapperTemplate)
404
    {
405 2
        $recipient = $this->recipientProvider->getRecipient($recipientId);
406
407
        // create new array for each recipient.
408 2
        $recipientParams = array_merge($params, $this->getRecipientSpecificNewsletterParams($recipient));
409
410
        // get the recipient-specific contentItems of the newsletter
411 2
        $recipientContentItems = $this->getRecipientSpecificNewsletterContentItems($recipient);
412
413
        // merge the recipient-specific and the general content items. recipient-specific first/at the top!
414 2
        $recipientParams[self::CONTENT_ITEMS] = $this->orderContentItems(array_merge($recipientContentItems,  $params[self::CONTENT_ITEMS]));
415 2
        $recipientParams['_locale'] = $recipient->getPreferredLocale();
416
417 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...
418 1
            $this->logger->warning("The newsletter for '".$recipient->getDisplayName()." <".$recipient->getEmail().">' has not been sent. It would have been empty.", $params);
419
420 1
            return $recipient->getEmail();
421
        }
422
423 1
        $subject = $this->getRecipientSpecificNewsletterSubject($params[self::CONTENT_ITEMS], $recipientContentItems, $params, $recipient, $recipient->getPreferredLocale());
424
425
        // render and send the email with the right wrapper-template
426 1
        $sent = $this->mailer->sendSingleEmail($recipient->getEmail(), $recipient->getDisplayName(), $subject, $recipientParams, $wrapperTemplate.".txt.twig", $recipient->getPreferredLocale());
427
428 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...
429
            // save that this recipient has recieved the newsletter
430 1
            return null;
431
432
        } else {
433 1
            $this->logger->error("The newsletter for ".$recipient->getDisplayName()." <".$recipient->getEmail()."> could not be sent!", $params);
434
435 1
            return $recipient->getEmail();
436
437
        }
438
    }
439
440
    /**
441
     * Get the Notifications that have not yet been sent yet.
442
     * Ordered by "template" and "title".
443
     * @param  RecipientInterface $recipient
444
     * @return array              of Notification
445
     */
446 3
    protected function getNotificationsFor(RecipientInterface $recipient)
447
    {
448
        // get the notification mode
449 3
        $notificationMode = $recipient->getNotificationMode();
450
451
        // get the date/time of the last notification
452 3
        $lastNotificationDate = $this->getNotificationRepository()->getLastNotificationDate($recipient->getId());
453
454 3
        $sendNotifications = false;
455 3
        $timeDelta = time() - $lastNotificationDate->getTimestamp();
456
457 3
        if ($notificationMode == RecipientInterface::NOTIFICATION_MODE_IMMEDIATELY) {
458 3
            $sendNotifications = true;
459
460 3
        } elseif ($notificationMode == RecipientInterface::NOTIFICATION_MODE_HOURLY) {
461 3
            $sendNotifications = ($timeDelta > $this->getHourInterval());
462
463 3
        } elseif ($notificationMode == RecipientInterface::NOTIFICATION_MODE_DAYLY) {
464 3
            $sendNotifications = ($timeDelta > $this->getDayInterval());
465
466 3
        } elseif ($notificationMode == RecipientInterface::NOTIFICATION_MODE_NEVER) {
467
            $this->markAllNotificationsAsSentFarInThePast($recipient);
468
469
            return array();
470
        }
471
472
        // regularly sent notifications now
473 3
        if ($sendNotifications) {
474 3
            $notifications = $this->getNotificationRepository()->getNotificationsToSend($recipient->getId());
475
476
        // if notifications exist, that should be sent immediately, then send those now disregarding the users mailing-preferences.
477 3
        } else {
478
            $notifications = $this->getNotificationRepository()->getNotificationsToSendImmediately($recipient->getId());
479
        }
480
481 3
        return $notifications;
482
    }
483
484
    /**
485
     * Get all IDs for Recipients of pending notifications
486
     * @return array of IDs
487
     */
488 3
    protected function getNotificationRecipientIds()
489
    {
490 3
        return $this->getNotificationRepository()->getNotificationRecipientIds();
491
    }
492
493
    /**
494
     * Update (set sent = now) and save the notifications
495
     * @param array $notifications
496
     */
497 2
    protected function setNotificationsAsSent(array $notifications)
498
    {
499 2
        foreach ($notifications as $notification) {
500 2
            $notification->setSent(new \DateTime());
501 2
            $this->managerRegistry->getManager()->persist($notification);
502 2
        }
503 2
        $this->managerRegistry->getManager()->flush();
504 2
    }
505
506
    /**
507
     * Mark all Notifications as sent long ago, as the recipient never want's to get any notifications.
508
     * @param RecipientInterface $recipient
509
     */
510 1
    protected function markAllNotificationsAsSentFarInThePast(RecipientInterface $recipient)
511
    {
512 1
        $this->getNotificationRepository()->markAllNotificationsAsSentFarInThePast($recipient->getId());
513 1
    }
514
515
    /**
516
     * Get the interval in days between newsletter mailings
517
     */
518 1
    protected function getNewsletterInterval()
519
    {
520 1
        return $this->configParameter[AzineEmailExtension::NEWSLETTER."_".AzineEmailExtension::NEWSLETTER_INTERVAL];
521
    }
522
523
    /**
524
     * Get the time of the day when the newsletter should be sent.
525
     * @return string Time of the day in the format HH:mm
526
     */
527 1
    protected function getNewsletterSendTime()
528
    {
529 1
        return $this->configParameter[AzineEmailExtension::NEWSLETTER."_".AzineEmailExtension::NEWSLETTER_SEND_TIME];
530
    }
531
532
    /**
533
     * Get the DateTime at which the last newsletter mailing probably has taken place, if a newsletter is sent today.
534
     * (Calculated: send-time-today - interval in days)
535
     * @return \DateTime
536
     */
537 1
    protected function getDateTimeOfLastNewsletter()
538
    {
539 1
        return new \DateTime($this->getNewsletterInterval()." days ago ".$this->getNewsletterSendTime());
540
    }
541
542
    /**
543
     * Get the DateTime at which the next newsletter mailing will take place, if a newsletter is sent today.
544
     * (Calculated: send-time-today + interval in days)
545
     */
546 1
    protected function getDateTimeOfNextNewsletter()
547
    {
548 1
        return new \DateTime("+".$this->getNewsletterInterval()." days  ".$this->getNewsletterSendTime());
549
    }
550
551
    /**
552
     * Convenience-function to add and save a Notification-entity
553
     *
554
     * @param  integer      $recipientId     the ID of the recipient of this notification => see RecipientProvider.getRecipient($id)
555
     * @param  string       $title           the title of the notification. depending on the recipients settings, multiple notifications are sent in one email.
556
     * @param  string       $content         the content of the notification
557
     * @param  string       $template        the twig-template to render the notification with
558
     * @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.
559
     * @param  integer      $importance      important messages are at the top of the notification-emails, un-important at the bottom.
560
     * @param  boolean      $sendImmediately whether or not to ignore the recipients mailing-preference and send the notification a.s.a.p.
561
     * @return Notification
562
     */
563 2
    public function addNotification($recipientId, $title, $content, $template, $templateVars, $importance, $sendImmediately)
564
    {
565 2
        $notification = new Notification();
566 2
        $notification->setRecipientId($recipientId);
567 2
        $notification->setTitle($title);
568 2
        $notification->setContent($content);
569 2
        $notification->setTemplate($template);
570 2
        $notification->setImportance($importance);
571 2
        $notification->setSendImmediately($sendImmediately);
572 2
        $notification->setVariables($templateVars);
573 2
        $this->managerRegistry->getManager()->persist($notification);
574 2
        $this->managerRegistry->getManager()->flush($notification);
575
576 2
        return $notification;
577
    }
578
579
    /**
580
     * Convenience-function to add and save a Notification-entity for a message => see AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TYPE
581
     *
582
     * The following default are used:
583
     * $importance		= NORMAL
584
     * $sendImmediately	= fale
585
     * $template		= template for type AzineTemplateProvider::CONTENT_ITEM_MESSAGE_TYPE
586
     * $templateVars	= only those from the template-provider
587
     *
588
     * @param integer $recipientId
589
     * @param string  $title
590
     * @param string  $content     nl2br will be applied in the html-version of the email
591
     * @param string  $goToUrl     if this is supplied, a link "Go to message" will be added.
592
     */
593 1
    public function addNotificationMessage($recipientId, $title, $content, $goToUrl = null)
594
    {
595 1
        $contentItemTemplate = $this->configParameter[AzineEmailExtension::TEMPLATES."_".AzineEmailExtension::CONTENT_ITEM_TEMPLATE];
596 1
        $templateVars = array();
597 1
        if ($goToUrl !== null && strlen($goToUrl) > 0) {
598 1
            $templateVars['goToUrl'] = $goToUrl;
599 1
        }
600 1
        $this->addNotification($recipientId, $title, $content, $contentItemTemplate, $this->templateProvider->addTemplateVariablesFor($contentItemTemplate, $templateVars), Notification::IMPORTANCE_NORMAL, false);
601 1
    }
602
603
604
    /**
605
     * @return NotificationRepository
606
     */
607 4
    protected function getNotificationRepository(){
608 4
        return $this->managerRegistry->getRepository('AzineEmailBundle:Notification');
609
    }
610
611
}
612