Passed
Push — dev5a ( 328ab1...cf3a23 )
by Ron
07:38
created

SetEmailProperties::saveEmailSettings()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
nc 12
nop 1
dl 0
loc 23
ccs 14
cts 14
cp 1
crap 5
rs 9.4888
c 1
b 0
f 0
1
<?php
2
3
namespace App\Domains\Admin;
4
5
use Illuminate\Mail\Mailer;
6
use Illuminate\Support\Facades\Log;
7
8
use App\Mail\TestEmail;
9
10
use Swift_Mailer;
11
use Swift_SmtpTransport;
12
13
class SetEmailProperties extends SettingsDomain
14
{
15
    //  Save the new Email Settings
16 4
    public function saveEmailSettings($request)
17
    {
18 4
        $username = $request->authentication ? $request->username : null;
19 4
        $password = $request->authentication ? $request->password : null;
20
        $mailSettings = [
21 4
            'mail.from.address' => $request->from_address,
22 4
            'mail.username'     => $username,
23 4
            'mail.password'     => $password,
24 4
            'mail.host'         => $request->host,
25 4
            'mail.port'         => $request->port,
26 4
            'mail.encryption'   => $request->encryption
27
        ];
28
29 4
        foreach($mailSettings as $key => $value)
30
        {
31 4
            $this->updateSettings($key, $value);
32 4
            if($key != 'mail.password')
33
            {
34 4
                Log::debug('Email Setting Key '.$key.' updated to '.$value);
35
            }
36
        }
37
38 4
        return true;
39
    }
40
41
    //  Send a test email using temporary credentials to verify if the settings are correct or not
42
    public function sendTestEmail($request, $emailAddress)
43
    {
44
        $password = $request->password === 'RandomString' ? config('mail.password') : $request->password;
45
46
        $transport = new Swift_SmtpTransport($request->host, $request->port);
47
        $transport->setUsername($request->username);
48
        $transport->setPassword($password);
49
        $transport->setEncryption($request->encryption);
50
51
        $swiftMailer = new Swift_Mailer($transport);
52
53
        $mail = new Mailer('Test Email', app()->get('view'), $swiftMailer);
54
        $mail->alwaysFrom($request->from_address);
55
        $mail->alwaysReplyTo($request->from_address);
56
57
        try
58
        {
59
            $mail->to($emailAddress)->send(new TestEmail);
60
            Log::info('Test email sent to '.$emailAddress);
61
        }
62
        catch (\Exception $e)
63
        {
64
            Log::alert('Test Email to '.$emailAddress.' failed.  Reason - ', array($e));
65
            return $e->getMessage();
66
        }
67
68
        return true;
69
    }
70
}
71