Completed
Push — master ( 893bae...47d70a )
by Roberto
06:02 queued 03:49
created

Mail::getXmlData()   D

Complexity

Conditions 16
Paths 324

Size

Total Lines 66
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 46.155

Importance

Changes 0
Metric Value
dl 0
loc 66
ccs 26
cts 51
cp 0.5098
rs 4.3619
c 0
b 0
f 0
cc 16
eloc 53
nc 324
nop 1
crap 46.155

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
namespace NFePHP\Mail;
4
5
/**
6
 * Class for sending emails related to SPED services
7
 *
8
 * @category  NFePHP
9
 * @package   NFePHP\Mail\Mail
10
 * @copyright NFePHP Copyright (c) 2016
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 $mailer = null)
40
    {
41
        $this->mail = $mailer;
42
        if (is_null($mailer)) {
43
            $this->mail = new PHPMailer();
44
        }
45
        $this->config = $config;
46
        $this->loadService($config);
47
        $this->fields = new \stdClass();
48
        $this->fields->destinatario = '';
49
        $this->fields->data = '';
50
        $this->fields->numero = '';
51
        $this->fields->valor = 0;
52
        $this->fields->chave = '';
53
        $this->fields->data = '';
54
        $this->fields->correcao = '';
55
        $this->fields->conduso = '';
56
    }
57
    
58
    /**
59
     * Load parameters to PHPMailer class
60
     * @param \stdClass $config
61
     */
62
    protected function loadService(\stdClass $config)
63
    {
64
        $this->mail->CharSet = 'UTF-8';
65
        $this->mail->isSMTP();
66
        $this->mail->Host = $config->host;
67
        $this->mail->SMTPAuth = true;
68
        $this->mail->Username = $config->user;
69
        $this->mail->Password = $config->password;
70
        $this->mail->SMTPSecure = $config->secure;
71
        $this->mail->Port = $config->port;
72
        $this->mail->setFrom($config->from, $config->fantasy);
73
        $this->mail->addReplyTo($config->replyTo, $config->replyName);
74
    }
75
    
76
    /**
77
     * Sets a template for body mail
78
     * If no template is passed, it will be used a standard template
79
     * see Base::class
80
     * @param string $htmlTemplate
81
     */
82 1
    public function loadTemplate($htmlTemplate)
83
    {
84 1
        if ($htmlTemplate != '') {
85 1
            $this->template = $htmlTemplate;
86
        }
87 1
    }
88
    
89
    /**
90
     * Load the documents to send
91
     * XML document is required, but PDF is not
92
     * @param string $xml content or path NFe, CTe or CCe in XML
93
     * @param string $pdf content or path document from NFe, CTe or CCe
94
     */
95
    public function loadDocuments($xml, $pdf = '')
96
    {
97
        $this->xml = $xml;
98
        $this->pdf = $pdf;
99
        if ($this->isFile($xml)) {
100
            $this->xml = file_get_contents($xml);
101
        }
102
        if ($this->isFile($pdf)) {
103
            $this->pdf = file_get_contents($pdf);
104
        }
105
        //get xml data
106
        $this->getXmlData($this->xml);
107
    }
108
    
109
    /**
110
     * Checks if given data is file, handles mixed input
111
     * @param  mixed $value
112
     * @return boolean
113
     */
114 2
    private function isFile($value)
115
    {
116 2
        $value = strval(str_replace("\0", "", $value));
117 2
        return is_file($value);
118
    }
119
    
120
    /**
121
     * Search xml for data
122
     * @param string $xml
123
     * @throws \InvalidArgumentException
124
     */
125 1
    protected function getXmlData($xml)
126
    {
127 1
        $dom = new \DOMDocument('1.0', 'UTF-8');
128 1
        $dom->preserveWhiteSpace = false;
129 1
        $dom->loadXML($xml);
130 1
        $root = $dom->documentElement;
131 1
        $name = $root->tagName;
132 1
        $dest = $dom->getElementsByTagName('dest')->item(0);
133 1
        $ide = $dom->getElementsByTagName('ide')->item(0);
134
        switch ($name) {
135 1
            case 'nfeProc':
136
            case 'NFe':
137 1
                $type = 'NFe';
138 1
                $this->fields->numero = $ide->getElementsByTagName('nNF')->item(0)->nodeValue;
139 1
                $this->fields->valor = $dom->getElementsByTagName('vNF')->item(0)->nodeValue;
140 1
                $this->fields->data = $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue;
141 1
                $this->subject = "NFe n. " . $this->fields->numero . " - " . $this->config->fantasy;
142 1
                break;
143
            case 'cteProc':
144
            case 'CTe':
145
                $type = 'CTe';
146
                $this->fields->numero = $ide->getElementsByTagName('nCT')->item(0)->nodeValue;
147
                $this->fields->valor = $dom->getElementsByTagName('vRec')->item(0)->nodeValue;
148
                $this->fields->data = $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue;
149
                $this->subject = "CTe n. " . $this->fields->numero . " - " . $this->config->fantasy;
150
                break;
151
            case 'procEventoNFe':
152
            case 'procEventoCTe':
153
                $type = 'CCe';
154
                $this->fields->chave = $dom->getElementsByTagName('chNFe')->item(0)->nodeValue;
155
                $this->fields->data = $dom->getElementsByTagName('dhEvento')->item(0)->nodeValue;
156
                $this->fields->correcao = $dom->getElementsByTagName('xCorrecao')->item(0)->nodeValue;
157
                $this->fields->conduso = $dom->getElementsByTagName('xCondUso')->item(0)->nodeValue;
158
                if (empty($this->fields->chave)) {
159
                    $this->fields->chave = $dom->getElementsByTagName('chCTe')->item(0)->nodeValue;
160
                }
161
                $this->subject = "Carta de Correção " . $this->config->fantasy;
162
                break;
163
            default:
164
                $type = '';
165
        }
166
        //get email adresses from xml, if exists
167
        //may have one address in <dest><email>
168 1
        if (!empty($dest)) {
169 1
            $this->fields->destinatario = $dest->getElementsByTagName('xNome')->item(0)->nodeValue;
170 1
            $email = !empty($dest->getElementsByTagName('email')->item(0)->nodeValue) ?
171 1
                $dest->getElementsByTagName('email')->item(0)->nodeValue : '';
172
        }
173 1
        if (!empty($email)) {
174 1
            $this->addresses[] = $email;
175
        }
176
        //may have others in <obsCont xCampo="email"><xTexto>[email protected]</xTexto>
177 1
        $obs = $dom->getElementsByTagName('obsCont');
178 1
        foreach ($obs as $ob) {
179
            if (strtoupper($ob->getAttribute('xCampo')) === 'EMAIL') {
180
                $this->addresses[] = $ob->getElementsByTagName('xTexto')->item(0)->nodeValue;
181
            }
182
        }
183
        //xml may be a NFe or a CTe or a CCe nothing else
184 1
        if ($type != 'NFe' && $type != 'CTe' && $type != 'CCe') {
185
            $msg = "Você deve passar apenas uma NFe ou um CTe ou um CCe. "
186
                    . "Esse documento não foi reconhecido.";
187
            throw new \InvalidArgumentException($msg);
188
        }
189 1
        $this->type = $type;
190 1
    }
191
    
192
    
193
    /**
194
     * Set all addresses including those that exists in the xml document
195
     * Send email only to listed addresses ignoring all email addresses in xml
196
     * @param array $addresses
197
     */
198 1
    protected function setAddresses(array $addresses = [])
199
    {
200 1
        if (!empty($addresses)) {
201 1
            $this->addresses = array_merge($this->addresses, $addresses);
202
        }
203 1
        $this->removeInvalidAdresses();
204 1
    }
205
    
206
    /**
207
     * Send mail
208
     * If no parameter was passed, only the email address contained in
209
     * the xml will be used
210
     * @param array $addresses
211
     * @return boolean
212
     * @throws \RuntimeException
213
     */
214 1
    public function send(array $addresses = [])
215
    {
216 1
        $this->setAddresses($addresses);
217 1
        if (empty($this->addresses)) {
218 1
            $msg = 'Não foram passados endereços de email validos !!';
219 1
            throw new \RuntimeException($msg);
220
        }
221
        foreach ($this->addresses as $address) {
222
            $this->mail->addAddress($address);
223
        }
224
        $body = $this->render();
225
        $this->mail->isHTML(true);
226
        $this->mail->Subject = $this->subject;
227
        $this->mail->Body = $body;
228
        $this->mail->AltBody = Html2Text::convert($body);
229
        $this->attach();
230
        if (!$this->mail->send()) {
231
            $msg = 'A mensagem não pode ser enviada. Mail Error: ' . $this->mail->ErrorInfo;
232
            throw new \RuntimeException($msg);
233
        }
234
        $this->mail->ClearAllRecipients();
235
        $this->mail->ClearAttachments();
236
        return true;
237
    }
238
    
239
    /**
240
     * Configure and send documents
241
     * @param \stdClass $config
242
     * @param type $xml
243
     * @param type $pdf
244
     * @param array $addresses
245
     * @param type $htmltemplate
246
     * @param PHPMailer $mailer
247
     * @return Mail
248
     */
249
    public static function sendMail(
250
        \stdClass $config,
251
        $xml,
252
        $pdf = '',
253
        array $addresses = [],
254
        $htmltemplate = '',
255
        PHPMailer $mailer = null
256
    ) {
257
        $mail = new static($config, $mailer);
258
        $mail->loadDocuments($xml, $pdf);
259
        $mail->loadTemplate($htmltemplate);
260
        $mail->send($addresses);
261
        return $mail;
262
    }
263
}
264