Passed
Branch master (249862)
by Adam
07:51
created

ChangeImageUrl::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 3
nop 1
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
1
<?php
2
3
namespace Coyote\Listeners;
4
5
use Illuminate\Mail\Events\MessageSending;
6
7
class ChangeImageUrl
8
{
9
    /**
10
     * Handle the event.
11
     *
12
     * @param  MessageSending  $event
13
     * @return void
14
     */
15
    public function handle(MessageSending $event)
16
    {
17
        $html = $event->message->getBody();
18
        $html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
19
20
        // ignore html errors
21
        libxml_use_internal_errors(true);
22
23
        $dom = new \DOMDocument;
24
        $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
25
26
        $images = $dom->getElementsByTagName('img');
27
28
        foreach ($images as $image) {
29
            $url = $image->getAttribute('src');
30
31
            if (!preg_match('#^[\w]+?://.*?#i', $url)) {
32
                $url = 'https:' . $url;
33
                $image->setAttribute('src', $url);
34
            }
35
        }
36
37
        $event->message->setBody(trim($dom->saveHTML()));
38
    }
39
}
40