Passed
Push — master ( 0033d3...25f054 )
by Roberto
03:38 queued 01:47
created

Mail::loadService()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 25
cp 0
rs 8.8977
c 0
b 0
f 0
cc 6
nc 16
nop 1
crap 42
1
<?php
2
3
namespace NFePHP\Mail;
4
5
/**
6
 * Class for sending emails related to SPED services
7
 *
8
 * @category  library
9
 * @package   NFePHP\Mail\Mail
10
 * @copyright NFePHP Copyright (c) 2008-2019
11
 * @license   http://www.gnu.org/licenses/lgpl.txt LGPLv3+
12
 * @license   https://opensource.org/licenses/MIT MIT
13
 * @license   http://www.gnu.org/licenses/gpl.txt GPLv3+
14
 * @author    Roberto L. Machado <linux.rlm at gmail dot com>
15
 * @link      http://github.com/nfephp-org/sped-mail for the canonical source repository
16
 */
17
18
use NFePHP\Mail\Base;
19
use PHPMailer;
20
use Html2Text\Html2Text;
21
22
class Mail extends Base
23
{
24
    /**
25
     * Html Body mail message
26
     * @var string
27
     */
28
    public $body;
29
    /**
30
     * Subject for email
31
     * @var string
32
     */
33
    public $subject;
34
35
    /**
36
     * Constructor
37
     * @param \stdClass $config
38
     */
39
    public function __construct(\stdClass $config)
40
    {
41
        $this->mail = new PHPMailer();
42
        
43
        $this->config = $config;
44
        $this->loadService($config);
45
        $this->fields = new \stdClass();
46
        $this->fields->destinatario = '';
47
        $this->fields->data = '';
48
        $this->fields->numero = '';
49
        $this->fields->valor = 0;
50
        $this->fields->chave = '';
51
        $this->fields->data = '';
52
        $this->fields->correcao = '';
53
        $this->fields->conduso = '';
54
    }
55
56
    /**
57
     * Load parameters to PHPMailer class
58
     * @param \stdClass $config
59
     */
60
    protected function loadService(\stdClass $config)
61
    {
62
        $this->mail->CharSet = 'UTF-8';
63
        $this->mail->isSMTP();
64
        $this->mail->Host = $config->host;
65
        $this->mail->SMTPAuth = $config->smtpauth;
66
        if (!empty($config->user) && !empty($config->password)) {
67
            $this->mail->SMTPAuth = true;
68
            $this->mail->Username = $config->user;
69
            $this->mail->Password = $config->password;
70
        }
71
        $this->mail->SMTPSecure = $config->secure;
72
        $this->mail->Port = $config->port;
73
        if (!empty($config->authtype)) {
74
            $this->mail->AuthType = $config->authtype;
75
        }
76
        if (!empty($config->timeout)) {
77
            $this->mail->Timeout = $config->timeout;
78
        }
79
        if (!empty($config->timelimit)) {
80
            $this->mail->Timelimit = $config->timelimit;
81
        }
82
        $this->mail->setFrom($config->from, $config->fantasy);
83
        $this->mail->addReplyTo($config->replyTo, $config->replyName);
84
    }
85
86
    /**
87
     * Sets a template for body mail
88
     * If no template is passed, it will be used a standard template
89
     * see Base::class
90
     * @param string $htmlTemplate
91
     */
92
    public function loadTemplate($htmlTemplate)
93
    {
94
        if ($htmlTemplate != '') {
95
            $this->template = $htmlTemplate;
96
        }
97
    }
98
99
    /**
100
     * Load the documents to send
101
     * XML document is required, but PDF is not
102
     * @param string $xml content or path NFe, CTe or CCe in XML
103
     * @param string $pdf content or path document from NFe, CTe or CCe
104
     */
105
    public function loadDocuments($xml, $pdf = '')
106
    {
107
        $this->xml = trim($xml);
108
        $this->pdf = trim($pdf);
109
        if ($this->isFile($this->xml)) {
110
            $this->xml = file_get_contents($this->xml);
111
        }
112
        if ($this->isFile($this->pdf)) {
113
            $this->pdf = file_get_contents($this->pdf);
114
        }
115
        //get xml data
116
        $this->getXmlData($this->xml);
117
    }
118
119
    /**
120
     * Checks if given data is file
121
     * @param  string $value
122
     * @return boolean
123
     */
124
    private function isFile($value)
125
    {
126
        //se a string for maior que 500bytes, provavelmente é o conteudo
127
        //de um xml ou de um PDF então verificar
128
        if (strlen($value) > 500
129
            && (substr($value, 0, 1) == '<' || substr($value, 0, 5) == "%PDF-")
130
        ) {
131
            return false;
132
        }
133
        //caso contrario pode ser um path muito longo !!
134
        $value = strval(str_replace("\0", "", $value));
135
        return is_file($value);
136
    }
137
138
    /**
139
     * Send mail
140
     * If no parameter was passed, only the email address contained in
141
     * the xml will be used
142
     * @param array $addresses
143
     * @return boolean
144
     * @throws \RuntimeException
145
     */
146
    public function send(array $addresses = [], $include = true)
147
    {
148
        $this->setAddresses($addresses, $include);
149
        if (empty($this->addresses)) {
150
            $msg = 'Não foram passados endereços de email validos !!';
151
            throw new \RuntimeException($msg);
152
        }
153
        foreach ($this->addresses as $address) {
154
            $this->mail->addAddress($address);
155
        }
156
        $body = $this->render();
157
        $this->mail->isHTML(true);
158
        $this->mail->Subject = $this->subject;
159
        $this->mail->Body = $body;
160
        $this->mail->AltBody = Html2Text::convert($body);
161
        $this->attach();
162
        if (!$this->mail->send()) {
163
            $msg = 'A mensagem não pode ser enviada. Mail Error: ' . $this->mail->ErrorInfo;
164
            throw new \RuntimeException($msg);
165
        }
166
        $this->mail->clearAllRecipients();
167
        $this->mail->clearAttachments();
168
        return true;
169
    }
170
171
    /**
172
     * Configure and send documents
173
     * @param \stdClass $config
174
     * @param string $xml
175
     * @param string $pdf
176
     * @param array $addresses
177
     * @param string $htmltemplate
178
     * @param PHPMailer $mailer
179
     * @return Mail
180
     */
181
    public static function sendMail(
182
        \stdClass $config,
183
        $xml,
184
        $pdf = '',
185
        array $addresses = [],
186
        $htmltemplate = '',
187
        PHPMailer $mailer = null
188
    ) {
189
        $mail = new static($config, $mailer);
0 ignored issues
show
Unused Code introduced by
The call to Mail::__construct() has too many arguments starting with $mailer.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
190
        $mail->loadDocuments($xml, $pdf);
191
        $mail->loadTemplate($htmltemplate);
192
        $mail->send($addresses, false);
193
        return $mail;
194
    }
195
}
196