Passed
Push — master ( 299f0a...0ff7d4 )
by Roberto
03:29 queued 10s
created

Danfce::setOffLineDoublePrint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace NFePHP\DA\NFe;
4
5
/**
6
 * Classe para a impressão em PDF do Documento Auxiliar de NFe Consumidor
7
 * NOTA: Esta classe não é a indicada para quem faz uso de impressoras térmicas ESCPOS
8
 *
9
 * @category  Library
10
 * @package   nfephp-org/sped-da
11
 * @copyright 2009-2020 NFePHP
12
 * @license   http://www.gnu.org/licenses/lesser.html LGPL v3
13
 * @link      http://github.com/nfephp-org/sped-da for the canonical source repository
14
 */
15
16
use DateTime;
17
use Exception;
18
use InvalidArgumentException;
19
use NFePHP\DA\Legacy\Dom;
20
use NFePHP\DA\Legacy\Pdf;
21
use NFePHP\DA\Common\DaCommon;
22
use Com\Tecnick\Barcode\Barcode;
23
24
class Danfce extends DaCommon
25
{
26
    protected $papel;
27
    protected $paperwidth = 80;
28
    protected $descPercent = 0.38;
29
    protected $xml; // string XML NFe
30
    protected $logomarca=''; // path para logomarca em jpg
31
    protected $formatoChave="#### #### #### #### #### #### #### #### #### #### ####";
32
    protected $nfeProc;
33
    protected $nfe;
34
    protected $infNFe;
35
    protected $ide;
36
    protected $enderDest;
37
    protected $ICMSTot;
38
    protected $imposto;
39
    protected $emit;
40
    protected $enderEmit;
41
    protected $qrCode;
42
    protected $urlChave;
43
    protected $det;
44
    protected $infAdic;
45
    protected $textoAdic;
46
    protected $tpEmis;
47
    protected $tpAmb;
48
    protected $pag;
49
    protected $vTroco;
50
    protected $itens = [];
51
    protected $dest;
52
    protected $imgQRCode;
53
    protected $urlQR = '';
54
    protected $pdf;
55
    protected $margem = 2;
56
    protected $flagResume = false;
57
    protected $hMaxLinha = 5;
58
    protected $hBoxLinha = 6;
59
    protected $hLinha = 3;
60
    protected $aFontTit = ['font' => 'times', 'size' => 9, 'style' => 'B'];
61
    protected $aFontTex = ['font' => 'times', 'size' => 8, 'style' => ''];
62
    protected $via = "Via Consumidor";
63
    protected $offline_double = true;
64
    protected $canceled = false;
65
66
    protected $bloco1H = 18.0; //cabecalho
67
    protected $bloco2H = 12.0; //informação fiscal
68
    
69
    protected $bloco3H = 0.0; //itens
70
    protected $bloco4H = 13.0; //totais
71
    protected $bloco5H = 0.0; //formas de pagamento
72
    
73
    protected $bloco6H = 10.0; //informação para consulta
74
    protected $bloco7H = 20.0; //informações do consumidor
75
    protected $bloco8H = 50.0; //informações do consumidor
76
    protected $bloco9H = 4.0; //informações sobre tributos
77
    protected $bloco10H = 5.0; //informações do integrador
78
79
    use Traits\TraitBlocoI;
80
    use Traits\TraitBlocoII;
81
    use Traits\TraitBlocoIII;
82
    use Traits\TraitBlocoIV;
83
    use Traits\TraitBlocoV;
84
    use Traits\TraitBlocoVI;
85
    use Traits\TraitBlocoVII;
86
    use Traits\TraitBlocoVIII;
87
    use Traits\TraitBlocoIX;
88
    use Traits\TraitBlocoX;
89
90
    /**
91
     * Construtor
92
     *
93
     * @param string $xml
94
     *
95
     * @throws Exception
96
     */
97
    public function __construct($xml)
98
    {
99
        $this->xml = $xml;
100
        if (empty($xml)) {
101
            throw new \Exception('Um xml de NFCe deve ser passado ao construtor da classe.');
102
        }
103
        //carrega dados do xml
104
        $this->loadXml();
105
    }
106
107
    /**
108
     * Seta a largura do papel de impressão em mm
109
     *
110
     * @param int $width
111
     */
112
    public function setPaperWidth($width = 80)
113
    {
114
        if ($width < 58) {
115
            throw new Exception("Largura insuficiente para a impressão do documento");
116
        }
117
        $this->paperwidth = $width;
118
    }
119
120
    /**
121
     * Seta margens de impressão em mm
122
     *
123
     * @param int $width
124
     */
125
    public function setMargins($width = 2)
126
    {
127
        if ($width > 4 || $width < 0) {
128
            throw new Exception("As margens devem estar entre 0 e 4 mm.");
129
        }
130
        $this->margem = $width;
131
    }
132
133
    /**
134
     * Seta a fonte a ser usada times ou arial
135
     *
136
     * @param string $font
137
     */
138
    public function setFont($font = 'times')
139
    {
140
        if (!in_array($font, ['times', 'arial'])) {
141
            $this->fontePadrao = 'times';
142
        } else {
143
            $this->fontePadrao = $font;
144
        }
145
    }
146
    
147
    /**
148
     * Seta a impressão para NFCe completa ou Simplificada
149
     *
150
     * @param bool $flag
151
     */
152
    public function setPrintResume($flag = false)
153
    {
154
        $this->flagResume = $flag;
155
    }
156
    
157
    /**
158
     * Marca como cancelada
159
     */
160
    public function setAsCanceled()
161
    {
162
        $this->canceled = true;
163
    }
164
    
165
    /**
166
     * Registra via do estabelecimento quando a impressção for offline
167
     */
168
    public function setViaEstabelecimento()
169
    {
170
        $this->via = "Via Estabelecimento";
171
    }
172
    
173
    /**
174
     * Habilita a impressão de duas vias quando NFCe for OFFLINE
175
     *
176
     * @param bool $flag
177
     */
178
    public function setOffLineDoublePrint($flag = true)
179
    {
180
        $this->offline_double = $flag;
181
    }
182
183
    /**
184
     * Renderiza o pdf
185
     *
186
     * @param string $logo
187
     * @return string
188
     */
189
    public function render($logo = '')
190
    {
191
        $this->monta($logo);
192
        //$this->papel = 80;
193
        return $this->pdf->getPdf();
194
    }
195
196
    protected function monta(
197
        $logo = ''
198
    ) {
199
        if (!empty($logo)) {
200
            $this->logomarca = $this->adjustImage($logo, true);
201
        }
202
        $tamPapelVert = $this->calculatePaperLength();
203
        $this->orientacao = 'P';
204
        $this->papel = [$this->paperwidth, $tamPapelVert];
205
        $this->logoAlign = 'L';
206
        $this->pdf = new Pdf($this->orientacao, 'mm', $this->papel);
0 ignored issues
show
Documentation introduced by
$this->papel is of type array<integer,integer|do...integer","1":"double"}>, 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...
207
208
        //margens do PDF, em milímetros. Obs.: a margem direita é sempre igual à
209
        //margem esquerda. A margem inferior *não* existe na FPDF, é definida aqui
210
        //apenas para controle se necessário ser maior do que a margem superior
211
        $margSup = $this->margem;
212
        $margEsq = $this->margem;
213
        $margInf = $this->margem;
214
        // posição inicial do conteúdo, a partir do canto superior esquerdo da página
215
        $xInic = $margEsq;
0 ignored issues
show
Unused Code introduced by
$xInic 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...
216
        $yInic = $margSup;
0 ignored issues
show
Unused Code introduced by
$yInic 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...
217
        $maxW = $this->paperwidth;
218
        $maxH = $tamPapelVert;
219
        //total inicial de paginas
220
        $totPag = 1;
0 ignored issues
show
Unused Code introduced by
$totPag 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...
221
        //largura imprimivel em mm: largura da folha menos as margens esq/direita
222
        $this->wPrint = $maxW-($margEsq*2);
0 ignored issues
show
Documentation Bug introduced by
The property $wPrint was declared of type double, but $maxW - $margEsq * 2 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
223
        //comprimento (altura) imprimivel em mm: altura da folha menos as margens
224
        //superior e inferior
225
        $this->hPrint = $maxH-$margSup-$margInf;
226
        // estabelece contagem de paginas
227
        $this->pdf->aliasNbPages();
228
        $this->pdf->setMargins($margEsq, $margSup); // fixa as margens
229
        $this->pdf->setDrawColor(0, 0, 0);
230
        $this->pdf->setFillColor(255, 255, 255);
231
        $this->pdf->open(); // inicia o documento
232
        $this->pdf->addPage($this->orientacao, $this->papel); // adiciona a primeira página
0 ignored issues
show
Documentation introduced by
$this->papel is of type array<integer,integer|do...integer","1":"double"}>, 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...
233
        $this->pdf->setLineWidth(0.1); // define a largura da linha
234
        $this->pdf->setTextColor(0, 0, 0);
235
236
        $y = $this->blocoI(); //cabecalho
237
        $y = $this->blocoII($y); //informação cabeçalho fiscal e contingência
238
        
239
        $y = $this->blocoIII($y); //informação dos itens
240
        $y = $this->blocoIV($y); //informação sobre os totais
241
        $y = $this->blocoV($y); //informação sobre pagamento
242
        
243
        $y = $this->blocoVI($y); //informações sobre consulta pela chave
244
        $y = $this->blocoVII($y); //informações sobre o consumidor e dados da NFCe
245
        $y = $this->blocoVIII($y); //QRCODE
246
        $y = $this->blocoIX($y); //informações sobre tributos
247
        $y = $this->blocoX($y); //creditos
0 ignored issues
show
Unused Code introduced by
$y 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...
248
        
249
        $ymark = $maxH/4;
250
        if ($this->tpAmb == 2) {
251
            $this->pdf->setTextColor(120, 120, 120);
252
            $texto = "SEM VALOR FISCAL\nEmitida em ambiente de homologacao";
253
            $aFont = ['font' => $this->fontePadrao, 'size' => 14, 'style' => 'B'];
254
            $ymark += $this->pdf->textBox(
255
                $this->margem,
256
                $ymark,
257
                $this->wPrint,
258
                $maxH/2,
259
                $texto,
260
                $aFont,
261
                'T',
262
                'C',
263
                false,
264
                '',
265
                false
266
            );
267
            $this->pdf->setTextColor(0, 0, 0);
268
        }
269
        if ($this->canceled) {
270
            $this->pdf->setTextColor(120, 120, 120);
271
            $texto = "CANCELADA";
272
            $aFont = ['font' => $this->fontePadrao, 'size' => 24, 'style' => 'B'];
273
            $this->pdf->textBox(
274
                $this->margem,
275
                $ymark+4,
276
                $this->wPrint,
277
                $maxH/2,
278
                $texto,
279
                $aFont,
280
                'T',
281
                'C',
282
                false,
283
                '',
284
                false
285
            );
286
            $this->pdf->setTextColor(0, 0, 0);
287
        }
288
        
289
        if (!$this->canceled && $this->tpEmis == 9 && $this->offline_double) {
290
            $this->setViaEstabelecimento();
291
            //não está cancelada e foi emitida OFFLINE e está ativada a dupla impressão
292
            $this->pdf->addPage($this->orientacao, $this->papel); // adiciona a primeira página
0 ignored issues
show
Documentation introduced by
$this->papel is of type array<integer,integer|do...integer","1":"double"}>, 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...
293
            $this->pdf->setLineWidth(0.1); // define a largura da linha
294
            $this->pdf->setTextColor(0, 0, 0);
295
            $y = $this->blocoI(); //cabecalho
296
            $y = $this->blocoII($y); //informação cabeçalho fiscal e contingência
297
            $y = $this->blocoIII($y); //informação dos itens
298
            $y = $this->blocoIV($y); //informação sobre os totais
299
            $y = $this->blocoV($y); //informação sobre pagamento
300
            $y = $this->blocoVI($y); //informações sobre consulta pela chave
301
            $y = $this->blocoVII($y); //informações sobre o consumidor e dados da NFCe
302
            $y = $this->blocoVIII($y); //QRCODE
303
            $y = $this->blocoIX($y); //informações sobre tributos
304
            $y = $this->blocoX($y); //creditos
0 ignored issues
show
Unused Code introduced by
$y 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...
305
            $ymark = $maxH/4;
306
            if ($this->tpAmb == 2) {
307
                $this->pdf->setTextColor(120, 120, 120);
308
                $texto = "SEM VALOR FISCAL\nEmitida em ambiente de homologacao";
309
                $aFont = ['font' => $this->fontePadrao, 'size' => 14, 'style' => 'B'];
310
                $ymark += $this->pdf->textBox(
311
                    $this->margem,
312
                    $ymark,
313
                    $this->wPrint,
314
                    $maxH/2,
315
                    $texto,
316
                    $aFont,
317
                    'T',
318
                    'C',
319
                    false,
320
                    '',
321
                    false
322
                );
323
            }
324
            $this->pdf->setTextColor(0, 0, 0);
325
        }
326
    }
327
328
329
    private function calculatePaperLength()
330
    {
331
        $wprint = $this->paperwidth - (2 * $this->margem);
332
        $this->bloco3H = $this->calculateHeightItens($wprint * $this->descPercent);
333
        $this->bloco5H = $this->calculateHeightPag();
334
        
335
        $length = $this->bloco1H //cabecalho
336
            + $this->bloco2H //informação fiscal
337
            + $this->bloco3H //itens
338
            + $this->bloco4H //totais
339
            + $this->bloco5H //formas de pagamento
340
            + $this->bloco6H //informação para consulta
341
            + $this->bloco7H //informações do consumidor
342
            + $this->bloco8H //qrcode
343
            + $this->bloco9H //informações sobre tributos
344
            + $this->bloco10H; //informações do integrador
345
        return $length;
346
    }
347
348
    /**
349
     * Carrega os dados do xml na classe
350
     * @param string $xml
0 ignored issues
show
Bug introduced by
There is no parameter named $xml. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
351
     *
352
     * @throws InvalidArgumentException
353
     */
354
    private function loadXml()
355
    {
356
        $this->dom = new Dom();
0 ignored issues
show
Bug introduced by
The property dom does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
357
        $this->dom->loadXML($this->xml);
358
        $this->ide = $this->dom->getElementsByTagName("ide")->item(0);
359
        $mod = $this->getTagValue($this->ide, "mod");
0 ignored issues
show
Unused Code introduced by
$mod 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...
360
        if ($this->getTagValue($this->ide, "mod") != '65') {
361
            throw new \Exception("O xml do DANFE deve ser uma NFC-e modelo 65");
362
        }
363
        $this->tpAmb = $this->getTagValue($this->ide, 'tpAmb');
364
        $this->nfeProc = $this->dom->getElementsByTagName("nfeProc")->item(0) ?? null;
365
        $this->infProt = $this->dom->getElementsByTagName("infProt")->item(0) ?? null;
0 ignored issues
show
Bug introduced by
The property infProt does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
366
        $this->nfe = $this->dom->getElementsByTagName("NFe")->item(0);
367
        $this->infNFe = $this->dom->getElementsByTagName("infNFe")->item(0);
368
        $this->emit = $this->dom->getElementsByTagName("emit")->item(0);
369
        $this->enderEmit = $this->dom->getElementsByTagName("enderEmit")->item(0);
370
        $this->det = $this->dom->getElementsByTagName("det");
371
        $this->dest = $this->dom->getElementsByTagName("dest")->item(0);
372
        $this->enderDest = $this->dom->getElementsByTagName("enderDest")->item(0);
373
        $this->imposto = $this->dom->getElementsByTagName("imposto")->item(0);
374
        $this->ICMSTot = $this->dom->getElementsByTagName("ICMSTot")->item(0);
375
        $this->tpImp = $this->ide->getElementsByTagName("tpImp")->item(0)->nodeValue;
0 ignored issues
show
Bug introduced by
The property tpImp does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
376
        $this->infAdic = $this->dom->getElementsByTagName("infAdic")->item(0);
377
        $this->tpEmis = $this->dom->getValue($this->ide, "tpEmis");
0 ignored issues
show
Documentation introduced by
$this->ide is of type object<DOMNode>, but the function expects a object<NFePHP\DA\Legacy\DOMElement>.

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...
378
        //se for o layout 4.0 busca pelas tags de detalhe do pagamento
379
        //senão, busca pelas tags de pagamento principal
380
        if ($this->infNFe->getAttribute("versao") == "4.00") {
381
            $this->pag = $this->dom->getElementsByTagName("detPag");
382
            $tagPag = $this->dom->getElementsByTagName("pag")->item(0);
383
            $this->vTroco = $this->getTagValue($tagPag, "vTroco");
384
        } else {
385
            $this->pag = $this->dom->getElementsByTagName("pag");
386
        }
387
        $this->qrCode = !empty($this->dom->getElementsByTagName('qrCode')->item(0)->nodeValue)
388
            ? $this->dom->getElementsByTagName('qrCode')->item(0)->nodeValue : null;
389
        $this->urlChave = !empty($this->dom->getElementsByTagName('urlChave')->item(0)->nodeValue)
390
            ? $this->dom->getElementsByTagName('urlChave')->item(0)->nodeValue : null;
391
        if (!empty($this->infProt)) {
392
            $cStat = $this->getTagValue($this->infProt, 'cStat');
393
            if ($cStat != 100) {
394
                $this->canceled = true;
395
            }
396
        }
397
    }
398
}
399