Completed
Push — master ( 49cca7...006e45 )
by Raffael
13:02 queued 09:25
created

Mail::setOptions()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 17
cp 0
rs 8.8571
c 0
b 0
f 0
cc 5
crap 30
eloc 12
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * balloon
7
 *
8
 * @copyright   Copryright (c) 2012-2018 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Balloon\App\Notification\Adapter;
13
14
use Balloon\App\Notification\MessageInterface;
15
use Balloon\Async\Mail as MailJob;
16
use Balloon\Server\User;
17
use Psr\Log\LoggerInterface;
18
use TaskScheduler\Async;
19
use Zend\Mail\Message;
20
use Zend\Mime\Message as MimeMessage;
21
use Zend\Mime\Part as MimePart;
22
23
class Mail implements AdapterInterface
24
{
25
    /**
26
     * Async.
27
     *
28
     * @var Async
29
     */
30
    protected $async;
31
32
    /**
33
     * Logger.
34
     *
35
     * @var LoggerInterface
36
     */
37
    protected $logger;
38
39
    /**
40
     * Constructor.
41
     */
42
    public function __construct(Async $async, LoggerInterface $logger)
43
    {
44
        $this->async = $async;
45
        $this->logger = $logger;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function notify(User $receiver, ?User $sender, MessageInterface $message, array $context = []): bool
52
    {
53
        $address = $receiver->getAttributes()['mail'];
54
        if (null === $address) {
55
            $this->logger->debug('skip mail notifcation for user ['.$receiver->getId().'], user does not have a valid mail address', [
56
                'category' => get_class($this),
57
            ]);
58
59
            return false;
60
        }
61
62
        $html = new MimePart($message->renderTemplate('mail_html.phtml', $receiver));
63
        $html->type = 'text/html';
64
        $html->setCharset('utf-8');
65
66
        $plain = new MimePart($message->renderTemplate('mail_plain.phtml', $receiver));
67
        $plain->type = 'text/plain';
68
        $plain->setCharset('utf-8');
69
        $body = new MimeMessage();
70
        $body->setParts([$html, $plain]);
71
72
        $mail = (new Message())
73
          ->setSubject($message->getSubject($receiver))
74
          ->setBody($body)
75
          ->setTo($address)
76
          ->setEncoding('UTF-8');
77
78
        $type = $mail->getHeaders()->get('Content-Type');
79
        $type->setType('multipart/alternative');
80
81
        $this->async->addJob(MailJob::class, $mail->toString(), [
82
            Async::OPTION_RETRY => 1,
83
        ]);
84
85
        return true;
86
    }
87
}
88