Passed
Pull Request — master (#404)
by Roberto
02:48
created

Danfce::setMargins()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 7
cp 0
crap 12
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 $canceled = false;
64
65
    protected $bloco1H = 18.0; //cabecalho
66
    protected $bloco2H = 12.0; //informação fiscal
67
    
68
    protected $bloco3H = 0.0; //itens
69
    protected $bloco4H = 13.0; //totais
70
    protected $bloco5H = 0.0; //formas de pagamento
71
    
72
    protected $bloco6H = 10.0; //informação para consulta
73
    protected $bloco7H = 20.0; //informações do consumidor
74
    protected $bloco8H = 50.0; //informações do consumidor
75
    protected $bloco9H = 4.0; //informações sobre tributos
76
    protected $bloco10H = 5.0; //informações do integrador
77
78
    use Traits\TraitBlocoI;
79
    use Traits\TraitBlocoII;
80
    use Traits\TraitBlocoIII;
81
    use Traits\TraitBlocoIV;
82
    use Traits\TraitBlocoV;
83
    use Traits\TraitBlocoVI;
84
    use Traits\TraitBlocoVII;
85
    use Traits\TraitBlocoVIII;
86
    use Traits\TraitBlocoIX;
87
    use Traits\TraitBlocoX;
88
89
    /**
90
     * Construtor
91
     *
92
     * @param string $xml
93
     *
94
     * @throws Exception
95
     */
96
    public function __construct($xml)
97
    {
98
        $this->xml = $xml;
99
        if (empty($xml)) {
100
            throw new \Exception('Um xml de NFCe deve ser passado ao construtor da classe.');
101
        }
102
        //carrega dados do xml
103
        $this->loadXml();
104
    }
105
106
    /**
107
     * Seta a largura do papel de impressão em mm
108
     *
109
     * @param int $width
110
     */
111
    public function setPaperWidth($width = 80)
112
    {
113
        if ($width < 58) {
114
            throw new Exception("Largura insuficiente para a impressão do documento");
115
        }
116
        $this->paperwidth = $width;
117
    }
118
119
    /**
120
     * Seta margens de impressão em mm
121
     *
122
     * @param int $width
123
     */
124
    public function setMargins($width = 2)
125
    {
126
        if ($width > 4 || $width < 0) {
127
            throw new Exception("As margens devem estar entre 0 e 4 mm.");
128
        }
129
        $this->margem = $width;
130
    }
131
132
    /**
133
     * Seta a fonte a ser usada times ou arial
134
     *
135
     * @param string $font
136
     */
137
    public function setFont($font = 'times')
138
    {
139
        if (!in_array($font, ['times', 'arial'])) {
140
            $this->fontePadrao = 'times';
141
        } else {
142
            $this->fontePadrao = $font;
143
        }
144
    }
145
    
146
    /**
147
     * Seta a impressão para NFCe completa ou Simplificada
148
     *
149
     * @param bool $flag
150
     */
151
    public function setPrintResume($flag = false)
152
    {
153
        $this->flagResume = $flag;
154
    }
155
    
156
    /**
157
     * Marca como cancelada
158
     */
159
    public function setAsCanceled()
160
    {
161
        $this->canceled = true;
162
    }
163
    
164
    /**
165
     * Registra via do estabelecimento quando a impressção for offline 
166
     */
167
    public function viaEstabelecimento()
168
    {
169
        $this->via = "Via Estabelecimento";
170
    }
171
172
    /**
173
     * Renderiza o pdf
174
     * 
175
     * @param string $logo
176
     * @return string
177
     */
178
    public function render($logo = '')
179
    {
180
        $this->monta($logo);
181
        //$this->papel = 80;
182
        return $this->pdf->getPdf();
183
    }
184
185
    protected function monta(
186
        $logo = ''
187
    ) {
188
        if (!empty($logo)) {
189
            $this->logomarca = $this->adjustImage($logo, true);
190
        }
191
        $tamPapelVert = $this->calculatePaperLength();
192
        $this->orientacao = 'P';
193
        $this->papel = [$this->paperwidth, $tamPapelVert];
194
        $this->logoAlign = 'L';
195
        $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...
196
197
        //margens do PDF, em milímetros. Obs.: a margem direita é sempre igual à
198
        //margem esquerda. A margem inferior *não* existe na FPDF, é definida aqui
199
        //apenas para controle se necessário ser maior do que a margem superior
200
        $margSup = $this->margem;
201
        $margEsq = $this->margem;
202
        $margInf = $this->margem;
203
        // posição inicial do conteúdo, a partir do canto superior esquerdo da página
204
        $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...
205
        $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...
206
        $maxW = $this->paperwidth;
207
        $maxH = $tamPapelVert;
208
        //total inicial de paginas
209
        $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...
210
        //largura imprimivel em mm: largura da folha menos as margens esq/direita
211
        $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...
212
        //comprimento (altura) imprimivel em mm: altura da folha menos as margens
213
        //superior e inferior
214
        $this->hPrint = $maxH-$margSup-$margInf;
215
        // estabelece contagem de paginas
216
        $this->pdf->aliasNbPages();
217
        $this->pdf->setMargins($margEsq, $margSup); // fixa as margens
218
        $this->pdf->setDrawColor(0, 0, 0);
219
        $this->pdf->setFillColor(255, 255, 255);
220
        $this->pdf->open(); // inicia o documento
221
        $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...
222
        $this->pdf->setLineWidth(0.1); // define a largura da linha
223
        $this->pdf->setTextColor(0, 0, 0);
224
225
        $y = $this->blocoI(); //cabecalho
226
        $y = $this->blocoII($y); //informação cabeçalho fiscal e contingência
227
        
228
        $y = $this->blocoIII($y); //informação dos itens
229
        $y = $this->blocoIV($y); //informação sobre os totais
230
        $y = $this->blocoV($y); //informação sobre pagamento
231
        
232
        $y = $this->blocoVI($y); //informações sobre consulta pela chave
233
        $y = $this->blocoVII($y); //informações sobre o consumidor e dados da NFCe
234
        $y = $this->blocoVIII($y); //QRCODE
235
        $y = $this->blocoIX($y); //informações sobre tributos
236
        $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...
237
        
238
        $ymark = $maxH/4;
239
        if ($this->tpAmb == 2) {
240
            $this->pdf->setTextColor(120, 120, 120);
241
            $texto = "SEM VALOR FISCAL\nEmitida em ambiente de homologacao";
242
            $aFont = ['font' => $this->fontePadrao, 'size' => 14, 'style' => 'B'];
243
            $ymark += $this->pdf->textBox(
244
                $this->margem,
245
                $ymark,
246
                $this->wPrint,
247
                $maxH/2,
248
                $texto,
249
                $aFont,
250
                'T',
251
                'C',
252
                false,
253
                '',
254
                false
255
            );
256
            $this->pdf->setTextColor(0, 0, 0);
257
        }
258
        if ($this->canceled) {
259
            $this->pdf->setTextColor(120, 120, 120);
260
            $texto = "CANCELADA";
261
            $aFont = ['font' => $this->fontePadrao, 'size' => 24, 'style' => 'B'];
262
            $this->pdf->textBox(
263
                $this->margem,
264
                $ymark+4,
265
                $this->wPrint,
266
                $maxH/2,
267
                $texto,
268
                $aFont,
269
                'T',
270
                'C',
271
                false,
272
                '',
273
                false
274
            );
275
            $this->pdf->setTextColor(0, 0, 0);
276
        }
277
    }
278
279
280
    private function calculatePaperLength()
281
    {
282
        $wprint = $this->paperwidth - (2 * $this->margem);
283
        $this->bloco3H = $this->calculateHeightItens($wprint * $this->descPercent);
284
        $this->bloco5H = $this->calculateHeightPag();
285
        
286
        $length = $this->bloco1H //cabecalho
287
            + $this->bloco2H //informação fiscal
288
            + $this->bloco3H //itens
289
            + $this->bloco4H //totais
290
            + $this->bloco5H //formas de pagamento
291
            + $this->bloco6H //informação para consulta
292
            + $this->bloco7H //informações do consumidor
293
            + $this->bloco8H //qrcode
294
            + $this->bloco9H //informações sobre tributos
295
            + $this->bloco10H; //informações do integrador
296
        return $length;
297
    }
298
299
    /**
300
     * Carrega os dados do xml na classe
301
     * @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...
302
     *
303
     * @throws InvalidArgumentException
304
     */
305
    private function loadXml()
306
    {
307
        $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...
308
        $this->dom->loadXML($this->xml);
309
        $this->ide = $this->dom->getElementsByTagName("ide")->item(0);
310
        $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...
311
        if ($this->getTagValue($this->ide, "mod") != '65') {
312
            throw new \Exception("O xml do DANFE deve ser uma NFC-e modelo 65");
313
        }
314
        $this->tpAmb = $this->getTagValue($this->ide, 'tpAmb');
315
        $this->nfeProc = $this->dom->getElementsByTagName("nfeProc")->item(0) ?? null;
316
        $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...
317
        $this->nfe = $this->dom->getElementsByTagName("NFe")->item(0);
318
        $this->infNFe = $this->dom->getElementsByTagName("infNFe")->item(0);
319
        $this->emit = $this->dom->getElementsByTagName("emit")->item(0);
320
        $this->enderEmit = $this->dom->getElementsByTagName("enderEmit")->item(0);
321
        $this->det = $this->dom->getElementsByTagName("det");
322
        $this->dest = $this->dom->getElementsByTagName("dest")->item(0);
323
        $this->enderDest = $this->dom->getElementsByTagName("enderDest")->item(0);
324
        $this->imposto = $this->dom->getElementsByTagName("imposto")->item(0);
325
        $this->ICMSTot = $this->dom->getElementsByTagName("ICMSTot")->item(0);
326
        $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...
327
        $this->infAdic = $this->dom->getElementsByTagName("infAdic")->item(0);
328
        $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...
329
        //se for o layout 4.0 busca pelas tags de detalhe do pagamento
330
        //senão, busca pelas tags de pagamento principal
331
        if ($this->infNFe->getAttribute("versao") == "4.00") {
332
            $this->pag = $this->dom->getElementsByTagName("detPag");
333
            $tagPag = $this->dom->getElementsByTagName("pag")->item(0);
334
            $this->vTroco = $this->getTagValue($tagPag, "vTroco");
335
        } else {
336
            $this->pag = $this->dom->getElementsByTagName("pag");
337
        }
338
        $this->qrCode = !empty($this->dom->getElementsByTagName('qrCode')->item(0)->nodeValue)
339
            ? $this->dom->getElementsByTagName('qrCode')->item(0)->nodeValue : null;
340
        $this->urlChave = !empty($this->dom->getElementsByTagName('urlChave')->item(0)->nodeValue)
341
            ? $this->dom->getElementsByTagName('urlChave')->item(0)->nodeValue : null;
342
        if (!empty($this->infProt)) {
343
            $cStat = $this->getTagValue($this->infProt, 'cStat');
344
            if ($cStat != 100) {
345
                $this->canceled = true;
346
            }
347
        }
348
    }
349
}
350