Passed
Push — master ( 38224a...a3a793 )
by Gabriel
02:06
created

MailSentListener::handle()   B

Complexity

Conditions 8
Paths 29

Size

Total Lines 29
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 22
c 1
b 0
f 0
nc 29
nop 1
dl 0
loc 29
rs 8.4444
1
<?php
2
3
namespace Giuga\LaravelMailLog\Listeners;
4
5
use Giuga\LaravelMailLog\Models\MailLog;
6
use Illuminate\Mail\Events\MessageSent;
7
use Illuminate\Support\Facades\Log;
8
9
class MailSentListener
10
{
11
    /**
12
     * Create the event listener.
13
     *
14
     * @return void
15
     */
16
    public function __construct()
17
    {
18
        //
19
    }
20
21
    /**
22
     * Handle the event.
23
     *
24
     * @param MessageSent $event
25
     * @return void
26
     */
27
    public function handle(MessageSent $event)
28
    {
29
        try {
30
            $msg = $event->message;
31
            $parts = $msg->getChildren();
32
            $body = $event->message->getBody();
33
            if (! empty($parts)) {
34
                foreach ($parts as $part) {
35
                    if (stripos($part->getBodyContentType(), 'image') !== false) {
36
                        $ptr = str_replace("\n", '', trim(str_replace($part->getHeaders(), '', $part->toString())));
37
                        $body = str_replace('cid:'.$part->getId(), 'data:'.$part->getBodyContentType().';base64,'.$ptr, $body);
38
                    }
39
                }
40
            }
41
42
            $to = $event->message->getTo() ?? [];
43
            $cc = $event->message->getCc() ?? [];
44
            $bcc = $event->message->getBcc() ?? [];
45
            $data = [
46
                'to' => implode(', ', is_array($to) ? array_keys($to) : $to),
0 ignored issues
show
introduced by
The condition is_array($to) is always true.
Loading history...
47
                'cc' => implode(', ', is_array($cc) ? array_keys($cc) : $cc),
0 ignored issues
show
introduced by
The condition is_array($cc) is always true.
Loading history...
48
                'bcc' => implode(', ', is_array($bcc) ? array_keys($bcc) : $bcc),
0 ignored issues
show
introduced by
The condition is_array($bcc) is always true.
Loading history...
49
                'subject' => $event->message->getSubject(),
50
                'message' => $body,
51
                'data' => [],
52
            ];
53
            MailLog::create($data);
54
        } catch (\Throwable $e) {
55
            Log::debug('Failed to save mail log ['.$e->getMessage().']');
56
        }
57
    }
58
}
59