Completed
Pull Request — master (#578)
by Richard
07:01
created

PhpMailerEmailProvider::mapEmail()   C

Complexity

Conditions 19
Paths 64

Size

Total Lines 67
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 19
eloc 43
nc 64
nop 2
dl 0
loc 67
rs 5.7441
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 You may not change or alter any portion of this comment or credits of supporting
4
 developers from this source code or any supporting source code which is considered
5
 copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
use Xmf\Module\Helper;
13
use Xoops\Core\Service\AbstractContract;
14
use Xoops\Core\Service\Contract\EmailInterface;
15
use Xoops\Core\Service\Response;
16
use Xoops\Core\Service\Data\Email;
17
18
use PHPMailer\PHPMailer\PHPMailer;
19
use PHPMailer\PHPMailer\Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Exception. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
20
21
/**
22
 * phpmailer module
23
 *
24
 * @copyright 2018 XOOPS Project (https://xoops.org)
25
 * @license   GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
26
 * @author    Richard Griffith <[email protected]>
27
 * @link      https://xoops.org
28
 */
29
class PhpMailerEmailProvider extends AbstractContract implements EmailInterface
30
{
31
    /**
32
     * getName - get a short name for this service provider. This should be unique within the
33
     * scope of the named service, so using module dirname is suggested.
34
     *
35
     * @return string - a unique name for the service provider
36
     */
37
    public function getName()
38
    {
39
        return 'phpmaileremail';
40
    }
41
42
    /**
43
     * getDescription - get human readable description of the service provider
44
     *
45
     * @return string
46
     */
47
    public function getDescription()
48
    {
49
        return 'Use PHPMailer for email.';
50
    }
51
52
    /**
53
     * @param \Xoops\Core\Service\Response     $response
54
     * @param \Xoops\Core\Service\Data\Message $email
55
     *
56
     * @return void - reports success or failure through $response->success
57
     */
58
    public function sendEmail(Response $response, Email $email)
59
    {
60
        try {
61
            $mailer = $this->setupMailer();
62
            $this->mapEmail($email, $mailer);
63
            $mailer->send();
64
        } catch (Exception $e) {
65
            $response->setSuccess(false)->addErrorMessage($e->getMessage());
66
        } catch (\Throwable $e) {
67
            $response->setSuccess(false)->addErrorMessage($e->getMessage());
68
            return;
69
        }
70
    }
71
72
    protected function mapEmail(Email $email, PHPMailer $mailer)
73
    {
74
        // Addresses
75
        $address = $email->getFromAddress();
76
        $mailer->setFrom($address->getEmail(), (string) $address->getDisplayName());
77
78
        $list = $email->getToAddresses();
79
        foreach ($list->getEachAddress() as $address) {
80
            $mailer->addAddress($address->getEmail(), (string) $address->getDisplayName());
81
        }
82
83
        $list = $email->getReplyToAddresses();
84
        if (null !== $list) {
85
            foreach ($list->getEachAddress() as $address) {
86
                $mailer->addReplyTo($address->getEmail(), (string)$address->getDisplayName());
87
            }
88
        }
89
90
        $list = $email->getCcAddresses();
91
        if (null !== $list) {
92
            foreach ($list->getEachAddress() as $address) {
93
                $mailer->addCC($address->getEmail(), (string)$address->getDisplayName());
94
            }
95
        }
96
97
        $list = $email->getBccAddresses();
98
        if (null !== $list) {
99
            foreach ($list->getEachAddress() as $address) {
100
                $mailer->addBCC($address->getEmail(), (string)$address->getDisplayName());
101
            }
102
        }
103
104
        // Attachments
105
        $attachmentSet = $email->getAttachments();
106
        if (null !== $attachmentSet) {
107
            foreach ($attachmentSet->getEachAttachment() as $attachment) {
108
                $file = $attachment->getFilename();
109
                $body = $attachment->getStringBody();
110
                $name = (string) $attachment->getName();
111
                $type = (string) $attachment->getMimeType();
112
                $inline = $attachment->getInlineAttribute();
113
                if (null !== $file && !$inline) {
114
                    $mailer->addAttachment($file, $name, 'base64', $type);
115
                } elseif (null === $file && !$inline) {
116
                    $mailer->addStringAttachment($body, $name, 'base64', $type);
117
                } elseif (null !== $file && $inline) {
118
                    $mailer->addEmbeddedImage($file, $name, $name, 'base64', $type);
119
                } elseif (null === $file && $inline) {
120
                    $mailer->addStringEmbeddedImage($body, $name, $name, 'base64', $type);
121
                }
122
            }
123
        }
124
125
        $mailer->CharSet = 'UTF-8';
126
        $mailer->Subject = $email->getSubject();
127
128
        if (null !== $email->getHtmlBody()) {
129
            $mailer->Body = $email->getHtmlBody();
130
            $mailer->AltBody = $email->getBody();
131
            $mailer->isHTML(true);
132
            return $mailer;
133
        }
134
135
        $mailer->isHTML(false);
136
        $mailer->Body= $email->getBody();
137
138
        return $mailer;
139
    }
140
141
    /**
142
     * Get a mailer instance with configured transport
143
     * @return \PHPMailer\PHPMailer\PHPMailer
144
     */
145
    protected function setupMailer() : PHPMailer
146
    {
147
        $mailer = new PHPMailer(true);
148
        $mailer->Debugoutput = \Xoops::getInstance()->logger();
149
        $helper = Helper::getHelper('phpmailer');
150
        // mailmethod = 'mail', 'sendmail', 'smtp', 'smtpauth'
151
152
        $mailmethod = $helper->getConfig('mailmethod', 'mail');
0 ignored issues
show
Bug introduced by
The method getConfig() does not exist on Xoops\Module\Helper. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

152
        /** @scrutinizer ignore-call */ 
153
        $mailmethod = $helper->getConfig('mailmethod', 'mail');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
153
        switch ($mailmethod) {
154
            case 'sendmail':
155
                $mailer->isSendmail();
156
                $mailer->Sendmail = $helper->getConfig('sendmailpath', $mailer->Sendmail);
157
                break;
158
            case 'smtpauth':
159
                $mailer->SMTPAuth = true;
160
                $mailer->Username = $helper->getConfig('smtp_user', '');
161
                $mailer->Password = $helper->getConfig('smtp_pass', '');
162
            // fallthrough
163
            case 'smtp':
164
                $mailer->isSMTP();
165
                $mailer->Host = $helper->getConfig('smtp_host', $mailer->Host);
166
                $mailer->SMTPAutoTLS = (bool) $helper->getConfig('smtp_usetls', true);
167
                $mailer->SMTPDebug = (int) $helper->getConfig('smtp_debug', 0);
168
                break;
169
            case 'mail':
170
            default:
171
                $mailer->isMail();
172
                break;
173
        }
174
        return $mailer;
175
    }
176
}
177