Passed
Push — master ( 53d961...28360b )
by Roberto
14:30 queued 11s
created

Complements::toAuthorize()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 10
cp 0
rs 9.9
c 0
b 0
f 0
cc 3
nc 2
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 != 'EnvEvento') {
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);
0 ignored issues
show
Unused Code introduced by
$proBPe is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
52
        if (empty($proNFe)) {
0 ignored issues
show
Bug introduced by
The variable $proNFe seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
53
            //not protocoladed NFe
54
            throw DocumentsException::wrongDocument(1);
55
        }
56
        $chaveBPe = $proNFe->getElementsByTagName('chBPe')->item(0)->nodeValue;
0 ignored issues
show
Unused Code introduced by
$chaveBPe is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
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 == $chaveNFe
0 ignored issues
show
Bug introduced by
The variable $chaveNFe does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
82
            ) {
83
                $proNFe->getElementsByTagName('cStat')
84
                    ->item(0)
85
                    ->nodeValue = '101';
86
                $proNFe->getElementsByTagName('nProt')
87
                    ->item(0)
88
                    ->nodeValue = $nProt;
89
                $proNFe->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 = $dig->nodeValue;
138
                if ($digProt == $digNFe && $chave == $key) {
0 ignored issues
show
Bug introduced by
The variable $digNFe does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
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 addEnvEventoProtocol($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 numero do lote do envio
179
        $envLote = $ev->getElementsByTagName('idLote')->item(0)->nodeValue;
180
        //extrai tag evento do xml origem (solicitação)
181
        $event = $ev->getElementsByTagName('evento')->item(0);
182
        $versao = $event->getAttribute('versao');
183
184
        $ret = new \DOMDocument('1.0', 'UTF-8');
185
        $ret->preserveWhiteSpace = false;
186
        $ret->formatOutput = false;
187
        $ret->loadXML($response);
188
        //extrai numero do lote da resposta
189
        $resLote = $ret->getElementsByTagName('idLote')->item(0)->nodeValue;
190
        //extrai a rag retEvento da resposta (retorno da SEFAZ)
191
        $retEv = $ret->getElementsByTagName('retEvento')->item(0);
192
        $cStat  = $retEv->getElementsByTagName('cStat')->item(0)->nodeValue;
193
        $xMotivo = $retEv->getElementsByTagName('xMotivo')->item(0)->nodeValue;
194
        $tpEvento = $retEv->getElementsByTagName('tpEvento')->item(0)->nodeValue;
195
        $cStatValids = ['135', '136'];
196
        if ($tpEvento == Tools::EVT_CANCELA) {
197
            $cStatValids[] = '155';
198
        }
199
        if (!in_array($cStat, $cStatValids)) {
200
            throw DocumentsException::wrongDocument(4, "[$cStat] $xMotivo");
201
        }
202
        if ($resLote !== $envLote) {
203
            throw DocumentsException::wrongDocument(
204
                5,
205
                "Os numeros de lote dos documentos são diferentes."
206
            );
207
        }
208
        return self::join(
209
            $ev->saveXML($event),
210
            $ret->saveXML($retEv),
211
            'procEventoBPe',
212
            $versao
213
        );
214
    }
215
216
    /**
217
     * Join the pieces of the source document with those of the answer
218
     * @param string $first
219
     * @param string $second
220
     * @param string $nodename
221
     * @param string $versao
222
     * @return string
223
     */
224
    protected static function join($first, $second, $nodename, $versao)
225
    {
226
        $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
227
                . "<$nodename versao=\"$versao\" "
228
                . "xmlns=\"".self::$urlPortal."\">";
229
        $xml .= $first;
230
        $xml .= $second;
231
        $xml .= "</$nodename>";
232
        return $xml;
233
    }
234
}
235