Passed
Pull Request — master (#58)
by
unknown
01:34
created

Mail::loadDocuments()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 12
cp 0
rs 9.8333
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 12
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, \PHPMailer\PHPMailer\PHPMailer $mailer = null)
40
    {
41
        $this->mail = $mailer;
42
        if (is_null($mailer)) {
43
            $this->mail = new \PHPMailer\PHPMailer\PHPMailer();
44
        }
45
        
46
        $this->config = $config;
47
        $this->loadService($config);
48
        $this->fields = new \stdClass();
49
        $this->fields->destinatario = '';
50
        $this->fields->data = '';
51
        $this->fields->numero = '';
52
        $this->fields->valor = 0;
53
        $this->fields->chave = '';
54
        $this->fields->data = '';
55
        $this->fields->correcao = '';
56
        $this->fields->conduso = '';
57
    }
58
59
    /**
60
     * Load parameters to PHPMailer class
61
     * @param \stdClass $config
62
     */
63
    protected function loadService(\stdClass $config)
64
    {
65
        $this->mail->CharSet = 'UTF-8';
66
        $this->mail->isSMTP();
67
        $this->mail->Host = $config->host;
68
        $this->mail->SMTPAuth = $config->smtpauth;
69
        if (!empty($config->user) && !empty($config->password)) {
70
            $this->mail->SMTPAuth = true;
71
            $this->mail->Username = $config->user;
72
            $this->mail->Password = $config->password;
73
        }
74
        $this->mail->SMTPSecure = $config->secure;
75
        $this->mail->Port = $config->port;
76
        if (!empty($config->authtype)) {
77
            $this->mail->AuthType = $config->authtype;
78
        }
79
        if (!empty($config->timeout)) {
80
            $this->mail->Timeout = $config->timeout;
81
        }
82
        if (!empty($config->timelimit)) {
83
            $this->mail->Timelimit = $config->timelimit;
84
        }
85
        if (is_array($config->smtpoptions)) {
86
        if (is_array($config->smtpoptions)) {
87
            $this->mail->SMTPOptions = $config->smtpoptions;
88
        }
89
        if (!empty($config->smtpdebug)) {
90
            $this->mail->SMTPDebug = $config->smtpdebug;
91
        }
92
        if (!empty($config->debugoutput)) {
93
            $this->mail->Debugoutput = $config->debugoutput;
94
        }
95
        $this->mail->setFrom($config->from, $config->fantasy);
96
        $this->mail->addReplyTo($config->replyTo, $config->replyName);
97
    }
98
99
    /**
100
     * Sets a template for body mail
101
     * If no template is passed, it will be used a standard template
102
     * see Base::class
103
     * @param string $htmlTemplate
104
     */
105
    public function loadTemplate($htmlTemplate)
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_PUBLIC
Loading history...
106
    {
107
        if ($htmlTemplate != '') {
108
            $this->template = $htmlTemplate;
109
        }
110
    }
111
112
    /**
113
     * Load the documents to send
114
     * XML document is required, but PDF is not
115
     * @param string $xml content or path NFe, CTe or CCe in XML
116
     * @param string $pdf content or path document from NFe, CTe or CCe
117
     */
118
    public function loadDocuments($xml, $pdf = '')
119
    {
120
        $this->xml = trim($xml);
121
        $this->pdf = trim($pdf);
122
        if ($this->isFile($this->xml)) {
123
            $this->xml = file_get_contents($this->xml);
124
        }
125
        if ($this->isFile($this->pdf)) {
126
            $this->pdf = file_get_contents($this->pdf);
127
        }
128
        //get xml data
129
        $this->getXmlData($this->xml);
130
    }
131
132
    /**
133
     * Checks if given data is file
134
     * @param  string $value
135
     * @return boolean
136
     */
137
    private function isFile($value)
138
    {
139
        //se a string for maior que 500bytes, provavelmente é o conteudo
140
        //de um xml ou de um PDF então verificar
141
        if (strlen($value) > 500
142
            && (substr($value, 0, 1) == '<' || substr($value, 0, 5) == "%PDF-")
143
        ) {
144
            return false;
145
        }
146
        //caso contrario pode ser um path muito longo !!
147
        $value = strval(str_replace("\0", "", $value));
148
        return is_file($value);
149
    }
150
151
    /**
152
     * Send mail
153
     * If no parameter was passed, only the email address contained in
154
     * the xml will be used
155
     * @param array $addresses
156
     * @return boolean
157
     * @throws \RuntimeException
158
     */
159
    public function send(array $addresses = [], $include = true)
160
    {
161
        $this->setAddresses($addresses, $include);
162
        if (empty($this->addresses)) {
163
            $msg = 'Não foram passados endereços de email validos !!';
164
            throw new \RuntimeException($msg);
165
        }
166
        foreach ($this->addresses as $address) {
167
            $this->mail->addAddress($address);
168
        }
169
        $body = $this->render();
170
        $this->mail->isHTML(true);
171
        $this->mail->Subject = $this->subject;
172
        $this->mail->Body = $body;
173
        $this->mail->AltBody = Html2Text::convert($body);
174
        $this->attach();
175
        if (!$this->mail->send()) {
176
            $msg = 'A mensagem não pode ser enviada. Mail Error: ' . $this->mail->ErrorInfo;
177
            throw new \RuntimeException($msg);
178
        }
179
        $this->mail->clearAllRecipients();
180
        $this->mail->clearAttachments();
181
        return true;
182
    }
183
184
    /**
185
     * Configure and send documents
186
     * @param \stdClass $config
187
     * @param string $xml
188
     * @param string $pdf
189
     * @param array $addresses
190
     * @param string $htmltemplate
191
     * @param PHPMailer $mailer
192
     * @return Mail
193
     */
194
    public static function sendMail(
195
        \stdClass $config,
196
        $xml,
197
        $pdf = '',
198
        array $addresses = [],
199
        $htmltemplate = '',
200
        PHPMailer $mailer = null
201
    ) {
202
        $mail = new static($config, $mailer);
203
        $mail->loadDocuments($xml, $pdf);
204
        $mail->loadTemplate($htmltemplate);
205
        $mail->send($addresses, false);
206
        return $mail;
207
    }
208
}
209