Passed
Pull Request — master (#12)
by
unknown
02:09
created

Complements::addEventoBPeProtocol()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 0
cts 30
cp 0
rs 9.392
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 12
1
<?php
2
3
namespace NFePHP\BPe;
4
5
use NFePHP\Common\Strings;
6
use NFePHP\BPe\Common\Standardize;
7
use NFePHP\BPe\Exception\DocumentsException;
8
use DOMDocument;
9
10
class Complements
11
{
12
    protected static $urlPortal = 'http://www.portalfiscal.inf.br/bpe';
13
14
    /**
15
     * Authorize document adding his protocol
16
     * @param string $request
17
     * @param string $response
18
     * @return string
19
     */
20
    public static function toAuthorize($request, $response)
21
    {
22
        $st = new Standardize();
23
        $key = ucfirst($st->whichIs($request));
24
        if ($key != 'BPe' && $key != 'EventoBPe') {
25
            //wrong document, this document is not able to recieve a protocol
26
            throw DocumentsException::wrongDocument(0, $key);
27
        }
28
        $func = "add".$key."Protocol";
29
        return self::$func($request, $response);
30
    }
31
32
    /**
33
     * Add cancel protocol to a autorized BPe
34
     * if event is not a cancellation will return
35
     * the same autorized NFe passing
36
     * NOTE: This action is not necessary, I use only for my needs to
37
     *       leave the BPe marked as Canceled in order to avoid mistakes
38
     *       after its cancellation.
39
     * @param  string $bpe content of autorized NFe XML
40
     * @param  string $cancelamento content of SEFAZ response
41
     * @return string
42
     * @throws \InvalidArgumentException
43
     */
44
    public static function cancelRegister($bpe, $cancelamento)
45
    {
46
        $procXML = $bpe;
47
        $dombpe = new DOMDocument('1.0', 'utf-8');
48
        $dombpe->formatOutput = false;
49
        $dombpe->preserveWhiteSpace = false;
50
        $dombpe->loadXML($bpe);
51
        $proBPe = $dombpe->getElementsByTagName('protBPe')->item(0);
52
        if (empty($proBPe)) {
53
            //not protocoladed NFe
54
            throw DocumentsException::wrongDocument(1);
55
        }
56
        $chaveBPe = $proBPe->getElementsByTagName('chBPe')->item(0)->nodeValue;
57
58
        $domcanc = new DOMDocument('1.0', 'utf-8');
59
        $domcanc->formatOutput = false;
60
        $domcanc->preserveWhiteSpace = false;
61
        $domcanc->loadXML($cancelamento);
62
        $eventos = $domcanc->getElementsByTagName('retEvento');
63
        foreach ($eventos as $evento) {
64
            $infEvento = $evento->getElementsByTagName('infEvento')->item(0);
65
            $cStat = $infEvento->getElementsByTagName('cStat')
66
                ->item(0)
67
                ->nodeValue;
68
            $nProt = $infEvento->getElementsByTagName('nProt')
69
                ->item(0)
70
                ->nodeValue;
71
            $chaveEvento = $infEvento->getElementsByTagName('chBPe')
72
                ->item(0)
73
                ->nodeValue;
74
            $tpEvento = $infEvento->getElementsByTagName('tpEvento')
75
                ->item(0)
76
                ->nodeValue;
77
            if (in_array($cStat, ['135', '136', '155'])
78
                && ($tpEvento == Tools::EVT_CANCELA
79
                    || $tpEvento == Tools::EVT_CANCELASUBSTITUICAO
80
                )
81
                && $chaveEvento == $chaveBPe
82
            ) {
83
                $proBPe->getElementsByTagName('cStat')
84
                    ->item(0)
85
                    ->nodeValue = '101';
86
                $proBPe->getElementsByTagName('nProt')
87
                    ->item(0)
88
                    ->nodeValue = $nProt;
89
                $proBPe->getElementsByTagName('xMotivo')
90
                    ->item(0)
91
                    ->nodeValue = 'Cancelamento de BPe homologado';
92
                $procXML = Strings::clearProtocoledXML($dombpe->saveXML());
93
                break;
94
            }
95
        }
96
        return $procXML;
97
    }
98
99
    /**
100
     * Authorize BPe
101
     * @param string $request
102
     * @param string $response
103
     * @return string
104
     * @throws \InvalidArgumentException
105
     */
106
    protected static function addBPeProtocol($request, $response)
107
    {
108
        $req = new DOMDocument('1.0', 'UTF-8');
109
        $req->preserveWhiteSpace = false;
110
        $req->formatOutput = false;
111
        $req->loadXML($request);
112
113
        $bpe = $req->getElementsByTagName('BPe')->item(0);
114
        $infBPe = $req->getElementsByTagName('infBPe')->item(0);
115
        $versao = $infBPe->getAttribute("versao");
116
        $chave = preg_replace('/[^0-9]/', '', $infBPe->getAttribute("Id"));
117
        $digBPe = $req->getElementsByTagName('DigestValue')
118
            ->item(0)
119
            ->nodeValue;
120
121
        $ret = new DOMDocument('1.0', 'UTF-8');
122
        $ret->preserveWhiteSpace = false;
123
        $ret->formatOutput = false;
124
        $ret->loadXML($response);
125
        $retProt = !empty($ret->getElementsByTagName('protBPe')) ? $ret->getElementsByTagName('protBPe') : null;
126
        if ($retProt === null) {
127
            throw DocumentsException::wrongDocument(3, "&lt;protBPe&gt;");
128
        }
129
        $digProt = '000';
130
        foreach ($retProt as $rp) {
131
            $infProt = $rp->getElementsByTagName('infProt')->item(0);
132
            $cStat = $infProt->getElementsByTagName('cStat')->item(0)->nodeValue;
133
            $xMotivo = $infProt->getElementsByTagName('xMotivo')->item(0)->nodeValue;
134
            $dig = $infProt->getElementsByTagName("digVal")->item(0);
135
            $key = $infProt->getElementsByTagName("chBPe")->item(0)->nodeValue;
136
            if (isset($dig)) {
137
                $digProt = base64_decode($dig->nodeValue);
138
                if ($digProt == $digBPe && $chave == $key) {
139
                    //100 Autorizado
140
                    //150 Autorizado fora do prazo
141
                    //110 Uso Denegado
142
                    //205 NFe Denegada
143
                    //301 Uso denegado por irregularidade fiscal do emitente
144
                    //302 Uso denegado por irregularidade fiscal do destinatário
145
                    //303 Uso Denegado Destinatario nao habilitado a operar na UF
146
                    $cstatpermit = ['100', '150', '110', '205', '301', '302', '303'];
147
                    if (!in_array($cStat, $cstatpermit)) {
148
                        throw DocumentsException::wrongDocument(4, "[$cStat] $xMotivo");
149
                    }
150
                    return self::join(
151
                        $req->saveXML($bpe),
152
                        $ret->saveXML($rp),
153
                        'bpeProc',
154
                        $versao
155
                    );
156
                }
157
            }
158
        }
159
        if ($digBPe !== $digProt) {
160
            throw DocumentsException::wrongDocument(5, "Os digest são diferentes");
161
        }
162
        return $req->saveXML();
163
    }
164
165
    /**
166
     * Authorize Event
167
     * @param string $request
168
     * @param string $response
169
     * @return string
170
     * @throws \InvalidArgumentException
171
     */
172
    protected static function addEventoBPeProtocol($request, $response)
173
    {
174
        $ev = new \DOMDocument('1.0', 'UTF-8');
175
        $ev->preserveWhiteSpace = false;
176
        $ev->formatOutput = false;
177
        $ev->loadXML($request);
178
        //extrai tag evento do xml origem (solicitação)
179
        $event = $ev->getElementsByTagName('evento')->item(0);
180
        $versao = $ev->getElementsByTagName('verAplic')->item(0);
181
182
        $ret = new \DOMDocument('1.0', 'UTF-8');
183
        $ret->preserveWhiteSpace = false;
184
        $ret->formatOutput = false;
185
        $ret->loadXML($response);
186
        //extrai a rag retEvento da resposta (retorno da SEFAZ)
187
        $retEv = $ret->getElementsByTagName('retEventoBPe')->item(0);
188
        $cStat  = $retEv->getElementsByTagName('cStat')->item(0)->nodeValue;
189
        $xMotivo = $retEv->getElementsByTagName('xMotivo')->item(0)->nodeValue;
190
        $tpEvento = $retEv->getElementsByTagName('tpEvento')->item(0)->nodeValue;
191
        $cStatValids = ['135', '136'];
192
        if ($tpEvento == Tools::EVT_CANCELA) {
193
            $cStatValids[] = '155';
194
        }
195
        if (!in_array($cStat, $cStatValids)) {
196
            throw DocumentsException::wrongDocument(4, "[$cStat] $xMotivo");
197
        }
198
        return self::join(
199
            $ev->saveXML($event),
200
            $ret->saveXML($retEv),
201
            'procEventoBPe',
202
            $versao
0 ignored issues
show
Documentation introduced by
$versao is of type object<DOMNode>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
203
        );
204
    }
205
206
    /**
207
     * Join the pieces of the source document with those of the answer
208
     * @param string $first
209
     * @param string $second
210
     * @param string $nodename
211
     * @param string $versao
212
     * @return string
213
     */
214
    protected static function join($first, $second, $nodename, $versao)
215
    {
216
        $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
217
                . "<$nodename versao=\"$versao\" "
218
                . "xmlns=\"".self::$urlPortal."\">";
219
        $xml .= $first;
220
        $xml .= $second;
221
        $xml .= "</$nodename>";
222
        return $xml;
223
    }
224
}
225